Java-MongoDB 将数组转换为 MongoCollection

Java-MongoDB Casting an array to a MongoCollection

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

JSON 共 Mongo

{
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)) returns 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 "";
 }