我想知道是否有可能在MongoDB中重新搜索数组中集合的文档。像这个例子:

Mongo的JSON

{
value1 : "aaa",
arrayvalue : [{
    value2 : "aaaaa",
    value3 : 1
    },{
    value2 : "aaaa",
    value3 : 2
    }]
}
{
value1 : "aaa",
arrayvalue : [{
    value2 : "bbbb",
    value3 : 3
    },{
    value2 : "bbbbb",
    value3 : 4
    }]
}


Java代码

public static String getValue3(){
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("test2");
    MongoCollection<Document> collection = db.getCollection("test1");
    if(collection == null)
        return "";
    Document doc = collection.find(and(eq("value1", "aaa"), eq("arrayvalue.value2", "aaaa"))).first();
    if(doc != null){
        MongoCollection<Document> arrayv = (MongoCollection<Document>) doc.get("arrayvalue");
        Document newdoc = arrayv.find(eq("value2", "aaaa")).first();
        return newdoc.get("value3").toString();
    }
    return "";
}


显然这是行不通的(正确的结果是“ 2”)。谁能帮我得到这个value3数字?

最佳答案

您可以简化查询以使用$elemMatch投影。

以下带有collection.find(filter)的代码projection(elemMatch(filter))返回带有单个匹配元素的arrayvalue,用于查询和投影过滤器。

doc.get("arrayvalue", List.class)读取arrayvalue,它将是[{value2 : "aaaa", value3 : 2}]

arrayValue.get(0).get("value3")读取value3

import static com.mongodb.client.model.Projections.elemMatch;

 public static String getValue3(){
      MongoClient mongoClient = new MongoClient("localhost", 27017);
      MongoDatabase db = mongoClient.getDatabase("test2");
      MongoCollection<Document> collection = db.getCollection("test1");
      if(collection == null)
        return "";
      Document doc = collection.find(eq("value1", "aaa")).projection(elemMatch("arrayvalue", eq("value2", "aaaa"))).first();
      if(doc != null) {
        List<Document> arrayValue = doc.get("arrayvalue", List.class);
        return arrayValue.get(0).get("value3").toString();
      }
      return "";
 }

07-26 04:13