如何在MongoDB Java中检索/查找嵌套数组的所有元素 [英] How to retrieve / find all elements of a nested array in MongoDB Java
本文介绍了如何在MongoDB Java中检索/查找嵌套数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将节点"数组中的所有元素查找/加载到Java列表或Hashmap中.
I am trying to find / load all elements in the "nodes" array into a Java List or Hashmap.
我正在处理无法修改的特定JSON格式. Mongo数据库集合仅包含一个文档,该文档如下所示.我正在尝试查询节点"数组的所有元素,但无法做到这一点.
I'm dealing with a specific JSON format that I cannot modify. The Mongo DB collection contains only one document, and that document is shown below. I am trying to query all elements of the "nodes" array but can't manage to do so.
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
Test2 returns NULL at the moment. I know I'm wrong but can't figure out how to do it. And here is the JSON
{
"_id": "12123434",
"nodes": [
{
"id": "1",
"name": "bla",
"attributes": [
"string1",
"string2"
]
},
{
"id": "2",
"name": "blabla",
"attributes": [
"string1",
"string2"
]
}
],
"groups": []
}
推荐答案
您只需要投影nodes
并进行映射.
You just need to project nodes
and map.
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();
这篇关于如何在MongoDB Java中检索/查找嵌套数组的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文