【发布时间】:2017-01-07 19:48:36
【问题描述】:
我正在尝试在 mongo + java 中使用 $regex 编写 $in 查询。它在 mongo shell 中运行良好,我得到了结果:
db.getCollection('collection').find({ "_id" : { "$in" : [ /^1332444344/]}})
但是,当我尝试从我的 java 应用程序执行时,我没有得到任何结果:
DBCollection collection = db.getCollection("collection");
BasicDBObject query = new BasicDBObject();
inQuery.put("_id", new BasicDBObject("$in", input));
DBCursor cursor = collection.find(query);
// This returns no results
// Query: { "_id" : { "$in" : [ { "$regex" : "/^1332444344/"} ] }}
input = Lists.newArrayList(Pattern.compile("/^1332444344/"));
// The following as well returned nothing
// Query: { "_id" : { "$in" : [ "/^1332444344/" ] }}
input = Lists.newArrayList("/^1332444344/"));
Java 代码在正则表达式周围添加双引号,这似乎是导致问题的原因。
我也尝试了以下方法,但遇到了 json 解析异常:
BasicQuery bq = new BasicQuery("{ \"_id\" : { \"$in\" : [ /^1332444344/ ]}}")
这个问题有解决办法吗?
谢谢
【问题讨论】:
-
我认为真正导致问题的是
/s。在字符串 (^) 的开头之前不能有/。 (Java 不使用/来表示正则表达式的开始和结束)。 -
“Java 代码在正则表达式周围添加双引号”:问:你到底是什么意思????问:您熟悉用于字符串文字的escape character (`\`) 吗?
-
非常感谢@AndyTurner。你说的对。 Lists.newArrayList(Pattern.compile("^1332444344")) 工作正常!
-
@paulsm4 表示引用导致了问题。因为以下内容没有从 mongo shell 返回结果: db.getCollection('collection').find({ "_id" : { "$in" : [ "/^1332444344/"]}})