[英]Using regular Expressions with Mongodb
I am using Java Spring to work with Mongodb. 我正在使用Java Spring与Mongodb一起工作。 I need to find documents which the word 'manager' is existed in description field.
我需要找到描述字段中存在“经理”一词的文档。 I tried following two method
我尝试了以下两种方法
Method 1 方法1
Query query = new Query();
query.addCriteria(Criteria.where("discription").regex("/\bmanager\b/"));
Method 2 方法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
我用这样的mongodb控制台尝试过
db.test.find({discription: {$regex: /\bmanager\b/}})
It worked as I expected. 它按我的预期工作。 What's wrong with my Java code.
我的Java代码有什么问题。
You don't have to add the slashes in the regex expression, as the regex method takes care of it. 您不必在regex表达式中添加斜杠,因为regex方法会处理它。 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()
. 看起来您可以直接使用正则表达式字符串,而无需使用
Pattern.compile()
。 Have you tried that? 你有尝试过吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.