假设我的结构为;
[
{id: 12, name: "alex" , children: [ 1, 2]},
{id: 1, name: "felix" , children: [ 17]},
{id: 17, name: "hannah" , children: []},
{id: 2, name: "jonnah" , children: [ 7]},
{id: 7, name: "tom" , children: [19]},
{id: 19, name: "angelica" , children: []}
]
当我输入id: 12
时,我想以“
{
"name":"alex",
"children":[
{
"name":"felix",
"children":[
{
"name":"hannah",
"children":[
]
}
]
},
{
"name":"jonnah",
"children":[
{
"name":"tom",
"children":[
{
"name":"angelica",
"children":[
]
}
]
}
]
}
]
}
我想在mongodb查询中执行此操作。是否可以在mongodb查询中递归跟踪树?
我尝试了$graphLookup
;
db.test.aggregate([
{
$graphLookup: {
from: "test",
startWith: "$children",
connectFromField: "children",
connectToField: "id",
as: "list"
}
}
]).pretty()
但是返回为;
{
"_id" : ObjectId("58cff1f823d40a3744b73f69"),
"id" : 12,
"name" : "alex",
"children" : [
1,
2
],
"list" : [
{
"_id" : ObjectId("58cff1f823d40a3744b73f6e"),
"id" : 19,
"name" : "angelica",
"children" : [ ]
},
{
"_id" : ObjectId("58cff1f823d40a3744b73f6a"),
"id" : 1,
"name" : "felix",
"children" : [
17
]
},
{
"_id" : ObjectId("58cff1f823d40a3744b73f6b"),
"id" : 17,
"name" : "hannah",
"children" : [ ]
},
{
"_id" : ObjectId("58cff1f823d40a3744b73f6c"),
"id" : 2,
"name" : "jonnah",
"children" : [
7
]
},
{
"_id" : ObjectId("58cff1f823d40a3744b73f6d"),
"id" : 7,
"name" : "tom",
"children" : [
19
]
}
]
}
{
"_id" : ObjectId("58cff1f823d40a3744b73f6a"),
"id" : 1,
"name" : "felix",
"children" : [
17
],
"list" : [
{
"_id" : ObjectId("58cff1f823d40a3744b73f6b"),
"id" : 17,
"name" : "hannah",
"children" : [ ]
}
]
}
{
"_id" : ObjectId("58cff1f823d40a3744b73f6b"),
"id" : 17,
"name" : "hannah",
"children" : [ ],
"list" : [ ]
}
{
"_id" : ObjectId("58cff1f823d40a3744b73f6c"),
"id" : 2,
"name" : "jonnah",
"children" : [
7
],
"list" : [
{
"_id" : ObjectId("58cff1f823d40a3744b73f6e"),
"id" : 19,
"name" : "angelica",
"children" : [ ]
},
{
"_id" : ObjectId("58cff1f823d40a3744b73f6d"),
"id" : 7,
"name" : "tom",
"children" : [
19
]
}
]
}
{
"_id" : ObjectId("58cff1f823d40a3744b73f6d"),
"id" : 7,
"name" : "tom",
"children" : [
19
],
"list" : [
{
"_id" : ObjectId("58cff1f823d40a3744b73f6e"),
"id" : 19,
"name" : "angelica",
"children" : [ ]
}
]
}
{
"_id" : ObjectId("58cff1f823d40a3744b73f6e"),
"id" : 19,
"name" : "angelica",
"children" : [ ],
"list" : [ ]
}
这不是我想要的确切返回类型。
EDIT2:
我希望$project
列表元素,如果子列表中包含list.id
。
我的意思是"name" : "alex"
我只想在列表中加入id: 1
和id: 2
。我该如何添加这个条件?
db.test.aggregate([
{
$graphLookup: {
from: "test",
startWith: "$children",
connectFromField: "children",
connectToField: "id",
as: "list"
}
},
{
$project: {
id: 1,
_id: 0,
"children" : 1,
list: 1,
//"children" : {$in : ["$list.id"]}
}
}
]).pretty()