我在玩MongoDB,我想将this tree重建为表示树的JSON对象:
{
"_id" : "Books",
"children" : [
{
"_id" : "Programming",
"children" : [
{
"_id": "Languages"
"children": []
},
{
"_id" : "Databases",
"children" : [
{
"_id": "MongoDB"
"children": []
},
{
"_id": "dbm"
"children": []
}
]
}
]
}
]
}
该树在数据库中表示为具有子引用的结构,与here完全相同。
正如我在教程中所读的那样,$ graphLookup聚合应该是一种方法,但是在执行这些聚合管道时:
[{$graphLookup: {
from: 'categories',
startWith: '$children',
connectFromField: 'children',
connectToField: '_id',
as: 'children',
maxDepth: 10
}}, {$match: {
"_id": "Books"
}}]
我有一个根“书”,每个孩子都直接连接到根:
{
"_id" : "Books",
"children" : [
{
"_id" : "dbm",
"children" : [ ]
},
{
"_id" : "Programming",
"children" : [ "Databases", "Languages" ]
},
{
"_id" : "Databases",
"children" : [ "MongoDB", "dbm" ]
},
{
"_id" : "Languages",
"children" : [ ] },
{
"_id" : "MongoDB",
"children" : [ ]
}
]
}
编辑:我问是否有一种方法只能通过使用mongodb查询来解决此问题,而没有js递归函数。