I'm trying to work with the new MongoDB v3.4 $graphLookup aggregation pipeline. I have this simple tree collection, with some nodes and a parent DBRef:
{ "_id" : ObjectId("59380657bbdbfb36c18a80f2"), "name" : "Root node 1" },
{ "_id" : ObjectId("5938068abbdbfb36c18a80f5"), "name" : "Child 1.1", "parent" : ObjectId("59380657bbdbfb36c18a80f2") },
{ "_id" : ObjectId("593806b0bbdbfb36c18a80f7"), "name" : "Subchild 1.1.1", "parent" : ObjectId("5938068abbdbfb36c18a80f5") },
{ "_id" : ObjectId("5938068abbdbfb36c18a80f6"), "name" : "Child 1.2", "parent" : ObjectId("59380657bbdbfb36c18a80f2") },
{ "_id" : ObjectId("59380657bbdbfb36c18a80f3"), "name" : "Root node 2" }
I would like to get this kind of tree structure:
- Root node 1
- Child 1.1
- Subchild 1.1.1
- Child 1.2
- Root node 2
So, I'm trying to work with the new $graphLookup aggregation pipeline, like this:
db.getCollection('tree').aggregate([
{ $match: { parent: { $exists: false } } },
{
$graphLookup: {
from: "tree",
startWith: "$_id",
connectFromField: "_id",
connectToField: "parent",
as: "children"
}
},
{ $sort: { name: 1 } }
])
But my issue is that I get all child of "Root node 1" in one collection:
{
"_id" : ObjectId("59380657bbdbfb36c18a80f2"),
"name" : "Root node 1",
"children" : [
{ "_id" : ObjectId("593806b0bbdbfb36c18a80f7"), "name" : "Subchild 1.1.1", "parent" : ObjectId("5938068abbdbfb36c18a80f5") },
{ "_id" : ObjectId("5938068abbdbfb36c18a80f6"), "name" : "Child 1.2", "parent" : ObjectId("59380657bbdbfb36c18a80f2") },
{ "_id" : ObjectId("5938068abbdbfb36c18a80f5"), "name" : "Child 1.1", "parent" : ObjectId("59380657bbdbfb36c18a80f2") }
]
},
{
"_id" : ObjectId("59380657bbdbfb36c18a80f3"),
"name" : "Root node 2",
"children" : [ ]
}
I have no idea how to lookup children recursively to get "Subchild 1.1.1" in the children collection of "Child 1.1". I'm looking for any suggestions. Thanks :)
所有评论(0)