gpt4 book ai didi

Java-MongoDB 将数组转换为 MongoCollection

转载 作者:行者123 更新时间:2023-12-02 13:26:51 26 4
gpt4 key购买 nike

我想知道是否可以在 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 "";
}

关于Java-MongoDB 将数组转换为 MongoCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43356687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com