MongoDB $graphLookup get children all levels deep - nested result

1,878 views
Skip to first unread message

Kyriakos Mandalas

unread,
Jun 8, 2018, 9:20:09 PM6/8/18
to mongodb-user

As presented in https://www.slideshare.net/mongodb/webinar-working-with-graph-data-in-mongodbslide 50 it is possible to use $graphLookup on a View in order to get a 2 levels deep tree-structure in nested format.


I have a MongoDB collection with tree nodes as documents with the following format:

{ "_id" : { "$oid" : "5b1a952361c6fa3418a15660" }, 
"nodeId" : 23978995, 
"name" : "settings", 
"type" : "Node",
"parentId" : [ 23978893, 23979072, 23979081 ] }


I have created a View like:

db.createView("treeView", "node", [
{
 $graphLookup: {
    from: "node",
    startWith: "$nodeId",
    connectFromField: "nodeId",
    connectToField: "parentId",
    maxDepth: 0,
    as: "children"
 }
}
]);


And I execute graph lookups like:

db.node.aggregate([ 
{ $match: {"nodeId": 23978786 } },
{
 $graphLookup: {
    from: "treeView",
    startWith: "$nodeId",
    connectFromField: "nodeId",
    connectToField: "parentId",
    maxDepth: 0,
    as: "children"
 }
}
]);


My question is how can I get the whole hierarchy, all levels deep?

Stephen Steneker

unread,
Jun 13, 2018, 10:10:02 PM6/13/18
to mongodb-user
Hi Kyriakos,

I noticed this question has also been posted (and answered) on Stack Overflow: https://stackoverflow.com/q/50767930/1388319.

Regards,
Stennie
Reply all
Reply to author
Forward
0 new messages