我正在尝试查找/加载"节点中的所有元素"数组到Java List或Hashmap。
我正在处理一些我无法修改的特定JSON格式。 Mongo数据库集合包含仅一个文档,该文档如下所示。我试图查询"节点的所有元素"数组,但无法设法这样做。
MongoCollection<Document> collection = mongoDB.getCollection(collectionName);
BasicDBObject query = new BasicDBObject();
query.put("nodes", "");
List<Document> test2 = collection.find(query).into(new ArrayList<Document>());
此时Test2返回NULL。我知道我错了,但无法弄清楚如何去做。 这是JSON
{
"_id": "12123434",
"nodes": [
{
"id": "1",
"name": "bla",
"attributes": [
"string1",
"string2"
]
},
{
"id": "2",
"name": "blabla",
"attributes": [
"string1",
"string2"
]
}
],
"groups": []
}
答案 0 :(得分:2)
您只需要投射nodes
并制作地图。
import static com.mongodb.client.model.Projections.*;
List<Document> nodes = (List<Document>) collection.find().projection(fields(include("nodes"), excludeId())).map(document -> document.get("nodes")).first();
答案 1 :(得分:0)
谢谢Sagar,您的代码段对我有很大帮助。 万一某人想要将过滤目标放在节点文档中的字段(例如-id)上,则可以使用以下内容。
List<Document> nodes = (List<Document>) collection.find().projection(elemMatch("nodes",new Document("id",2))).map(document -> document.get("nodes")).first();