gpt4 book ai didi

Java MongoDB访问对象子节点

转载 作者:行者123 更新时间:2023-12-02 07:31:34 25 4
gpt4 key购买 nike

我将以下文档从 MongoDB 提取到 Java 中:

{
"_id": {
"$oid": "5076371389d22e8906000000"
},
"item": {
"values": [
{
"value1": [
4958,
3787,
344
],
"value2": [
4,
13,
23
]
}
],
"name": "item1"
}
}

使用

M mongo = new M("database", "collection");
String query = "{\"item.name\":\"item1\"}";
DBCursor cur = mongo.collection.find(mongo.query(query));
while(cur.hasNext()) {
System.out.println(cur.next().toString());
// I need to access value1 array.
}

我需要访问 value1 数组,我还需要拉取整个文档,所以我不能只要求 Mongo 为我返回这个。就像我拉动这个文档,需要进行计算并再次使用该文档。我知道这个结果可以转换为 map 。但由于它是一个多维对象,我如何能够浏览它。谢谢

最佳答案

试试这个:

  //try catch omitted
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("db");

BasicDBObject query = new BasicDBObject("item.name","item1");
DBCursor cur = db.getCollection("items").find(query);
while(cur.hasNext()) {
BasicDBObject object = (BasicDBObject) cur.next();
BasicDBObject item = (BasicDBObject) object.get("item");
BasicDBList valueslist = (BasicDBList) item.get("values");
BasicDBObject values = (BasicDBObject) valueslist.get(0);
BasicDBList value1 = (BasicDBList) values.get("value1");
System.out.println(value1);
}

您可以优化它,但我希望您明白这一点并且它会有所帮助。干杯

关于Java MongoDB访问对象子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12847808/

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