[英]MongoDB Java client using $regex with $in
I am using the MongoDB Java client to query data: 我正在使用MongoDB Java客户端来查询数据:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.5.0</version>
</dependency>
The server version is 3.4.10. 服务器版本为3.4.10。
When using the MongoDB shell, I can successfully query using: 使用MongoDB Shell时,我可以使用以下命令成功查询:
db.c1.find(
{ title: { $in: [/test/,/demo/] } },
{ title:1 }
)
But when using the Java driver it does not work. 但是当使用Java驱动程序时,它不起作用。 For example:
例如:
List<String> keywords = new ArrayList<>();
keywords.add("/test/");
keywords.add("/demo/");
Document titleRegEx = new Document("$in", keywords);
Document filter = new Document("title", titleRegEx);
Document firstDoc = coll.find(filter).first();
logger.info("firstDoc: {}", firstDoc);
Please help me out. 请帮帮我。
If you profile the MongoDB calls you'll see that this 'find statement' ... 如果您配置了MongoDB调用,您将看到此“查找语句” ...
List<String> keywords = new ArrayList<>();
keywords.add("/test/");
keywords.add("/demo/");
Document titleRegEx = new Document("$in", keywords);
Document filter = new Document("title", titleRegEx);
Document firstDoc = coll.find(filter).first();
... causes the following filter to be submitted to MongoDB: ...导致以下过滤器提交给MongoDB:
filter: { title: { $in: [ "/test/", "/demo/" ] } } }
Note the value of the $in
document; 注意
$in
文档中的值; instead of $in: [/test/,/demo/]
it is: $in: [ "/test/", "/demo/" ]
. 而不是
$in: [/test/,/demo/]
而是$in: [ "/test/", "/demo/" ]
。 So, it is performing exact string matches on "/test/" and "/demo/" rather than regex matches. 因此,它在“ / test /”和“ / demo /”上执行精确的字符串匹配,而不是正则表达式匹配。 This explains why this 'find statement' returns nothing.
这解释了为什么此“查找语句”什么也不返回。
You engage a regex search when using the Java driver like so: 使用Java驱动程序时,您需要进行正则表达式搜索,如下所示:
Filters.regex("title", "test")
The MongoDB Java driver does not allow you to supply a collection of Bson
instances for $in
so if you want to search for documents which match one of the elements in this 'in' list: /test/, /demo/
then you have to form an OR
query. MongoDB Java驱动程序不允许您为
$in
提供Bson
实例的集合,因此,如果您要搜索与“ in”列表中的元素之一匹配的文档: /test/, /demo/
则必须形成一个OR
查询。 For example: 例如:
Bson filter = Filters.or(Filters.regex("title", "test"), Filters.regex("title", "demo"));
FindIterable<Document> documents = collection.find(filter);
If you profile the MongoDB calls you'll see that the above code causes the following 'find statement' to be executed on MongoDB: 如果您对MongoDB调用进行概要分析,您将看到上面的代码使以下“ find语句”在MongoDB上执行:
find { find: "posts", filter: { $or: [ { title: /test/ }, { title: /demo/ } ] } }
This is functionally equivalent to the command you showed in your question. 这在功能上等同于您在问题中显示的命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.