您需要$ graphLookup在MongoDB中运行递归查询。获得对象及其所有对象的父对象后,可以运行$ concatArrays创建一个数组,然后将$ unwind与$ replaceRoot结合使用以在结果集中获取多个文档:
db.collection.aggregate( [
{
$graphLookup: {
from: "collection",
startWith: "$parent_org",
connectFromField: "parent_org",
connectToField: "_id",
as: "hierarchy"
}
},
{
$match: {
_id: 4
}
},
{
$project: {
result: {
$concatArrays: [ "$hierarchy", [ { _id: "$_id", "org_name": "$org_name", parent_org: "$parent_org" } ] ]
}
}
},
{
$unwind: "$result"
},
{
$replaceRoot: {
newRoot: "$result"
}
},
{
$sort: {
_id: 1
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句