简体   繁体   English

Java 中 MongoDB 文档数组的精确文本匹配

[英]Exact text match on MongoDB document array in Java

I am trying to retrieve a single document (first) from a collection using an exact match on the MongoDB collection in Java.我正在尝试使用 Java 中 MongoDB 集合的完全匹配从集合中检索单个文档(第一个)。

The collection is as follows:合集如下:

{ "_id": 1, "color": "red", "qty": 5, "vendor": ["Vendor A"] }
{ "_id": 2, "color": "purple", "qty": 10, "vendor": ["Vendor C", "Vendor D"] }
{ "_id": 3, "color": "blue", "qty": 8, "vendor": ["Vendor B", "Vendor A"] }
{ "_id": 4, "color": "white", "qty": 6, "vendor": ["Vendor"] }

I want to query and return the document by searching for "Vendor" (string: keySearch) in the vendor tags:我想通过在供应商标签中搜索“供应商”(字符串:keySearch)来查询并返回文档:

{ "_id": 4, "color": "white", "qty": 6, "vendor": ["Vendor"] }

But, the following code I wrote returns the first document instead:但是,我编写的以下代码改为返回第一个文档:

Bson filter = Filters.text("\"" + keySearch + "\"");
Document doc = collection.find(filter).first();

I also tried the following, but this returns nothing:我也尝试了以下,但这没有返回:

Bson elemInArrayMatch = elemMatch("vendor", eq(keySearch));
Document doc = collection.find(elemInArrayMatch).first();

I want to perform an exact match on the vendor tag, ie, when the keySearch is "Vendor" it should return (in this case) only one document, ID: 4. Can anyone help me please?我想对供应商标签执行精确匹配,即,当 keySearch 为“Vendor”时,它应该(在本例中)仅返回一个文档,ID:4。有人可以帮我吗?

In Java you can do something like:在 Java 中,您可以执行以下操作:

private static void findExample(DBCollection collection) {
    BasicDBObject Query = new BasicDBObject();
    Query.put("vendor","Vendor");
    DBCursor cursor = collection.find(Query);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
}

example from mongoDB java docs here来自 mongoDB java 文档的示例在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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