简体   繁体   中英

Using regular Expressions with Mongodb

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM