使用$graphLookup流水线阶段。
查询:
db.getCollection('t').aggregate([
{
$group: {
_id: null,
names: { $addToSet: "$name" },
childs: { $addToSet: "$child" }
}
},
{
$addFields: {
roots: { $setDifference: ["$names", "$childs"] }
}
},
{ $unwind: "$roots" },
{
$graphLookup: {
from: "t",
startWith: "$roots",
connectFromField: "child",
connectToField: "name",
as: "related"
}
},
{
$project: {
"related": 1,
"_id": 0
}
}
])
结果:
/* 1 */
{
"related" : [
{
"_id" : ObjectId("5a29316a545eb40950c33bc8"),
"name" : "C"
},
{
"_id" : ObjectId("5a29316a545eb40950c33bc7"),
"name" : "B",
"child" : "C"
},
{
"_id" : ObjectId("5a29316a545eb40950c33bc6"),
"name" : "A",
"child" : "B"
}
]
}
/* 2 */
{
"related" : [
{
"_id" : ObjectId("5a29316a545eb40950c33bca"),
"name" : "E"
},
{
"_id" : ObjectId("5a29316a545eb40950c33bc9"),
"name" : "D",
"child" : "E"
}
]
}