0

I am using Java Spring to work with Mongodb. I need to find documents which the word 'manager' is existed in description field. I tried following two method

Method 1

Query query = new Query();
query.addCriteria(Criteria.where("discription").regex("/\bmanager\b/"));

Method 2

Query query = new Query();
Pattern p = Pattern.compile("/\bmanager\b/");
query.addCriteria(Criteria.where("discription").regex(p));

But none of these were worked. I tried it with mongodb console like this

db.test.find({discription: {$regex: /\bmanager\b/}})

It worked as I expected. What's wrong with my Java code.

2 Answers 2

1

You don't have to add the slashes in the regex expression, as the regex method takes care of it. So

Query query = new Query();
query.addCriteria(Criteria.where("description").regex("\bmanager\b"));

should work.

Sign up to request clarification or add additional context in comments.

5 Comments

Then you are doing something else wrong. Have a look here: mkyong.com/mongodb/spring-data-mongodb-like-query-example
Maybe you should use BasicQuery instead of query. Another way would be to use SpringData's repository feature.
I can get it work if I use regular expression as "manager" without enclosing it with '\b \b'. But that's not the result I expected. I want 'manager' as a whole word. I think the problem here is using '\b \b'
You might have to escape the slashes.
If I print the query object it looks like this. Query: { "description" : { "$regex" : "/\bmanager\b/"}}. The regular expression string has enclosed with double quotations here. That's the problem I think.
0

It looks like you can just pass your regex string straight through without using Pattern.compile(). Have you tried that?

4 Comments

doh. missed that. is it really discription in the db and not description?
:) Just a typing mistake. It should be description.
But the problem is still exist
Yeah, i don't know spring-data so I'm not sure what else to suggest except step through how regex() works and see what the final generated query looks like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.