您可以嘗試黑客使用的$lookup
和$unwind
運營商如下聚合管道:
db.collection.aggregate([
{
"$unwind": {
"path": "$children",
"preserveNullAndEmptyArrays": true
}
},
{
"$lookup": {
"from": "test",
"localField": "children",
"foreignField": "doc",
"as": "child"
}
},
{
"$unwind": {
"path": "$child",
"preserveNullAndEmptyArrays": true
}
},
{
"$unwind": {
"path": "$child.children",
"preserveNullAndEmptyArrays": true
}
},
{
"$lookup": {
"from": "test",
"localField": "child.children",
"foreignField": "doc",
"as": "child.child"
}
},
{
"$unwind": {
"path": "$child.child",
"preserveNullAndEmptyArrays": true
}
},
{
"$unwind": {
"path": "$child.child.children",
"preserveNullAndEmptyArrays": true
}
},
{
"$lookup": {
"from": "test",
"localField": "child.child.children",
"foreignField": "doc",
"as": "child.child.child"
}
},
{
"$unwind": {
"path": "$child.child.child",
"preserveNullAndEmptyArrays": true
}
},
{
"$unwind": {
"path": "$child.child.child.children",
"preserveNullAndEmptyArrays": true
}
},
{
"$group": {
"_id": "$doc",
"children": { "$push": "$child" }
}
},
{ "$match": { "_id": "a" } }
])
樣本輸出
{
"_id" : "a",
"children" : [
{
"_id" : ObjectId("58204f0cd3cda4b4b1adadfb"),
"doc" : "b",
"children" : "d",
"child" : {
"_id" : ObjectId("58204f0cd3cda4b4b1adadfd"),
"doc" : "d"
}
},
{
"_id" : ObjectId("58204f0cd3cda4b4b1adadfc"),
"doc" : "c",
"children" : "e",
"child" : {
"_id" : ObjectId("58204f0cd3cda4b4b1adadfe"),
"doc" : "e",
"children" : "f",
"child" : {
"_id" : ObjectId("58204f0cd3cda4b4b1adadff"),
"doc" : "f"
}
}
}
]
}
我認爲你需要更清楚 –
對於給定的文件,我想檢索所有的孩子以及每個孩子的孩子等等。 – user606521
你的遍歷順序問題,即abdcef?或者它也可以是acefbd? – sergiuz