Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

aggregation framework - MongoDB $graphLookup get children all levels deep - nested result

As presented in https://www.slideshare.net/mongodb/webinar-working-with-graph-data-in-mongodb, slide 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately, you can't get the full depth in a nested format. Using a view is a workaround which lets you perform that operation, but you would need to create a new view for each level of embedding that you need. Instead, I would consider performing a graphLookup without providing a depth, starting from the root level, fetching all the hierarchy in a single query, before computing the tree at the application level.

This would look like something like this:

db.node.aggregate([
    { $match: {
        parentId: null
    }},
    { $graphLookup: {
        from: "node",
        startWith: "$nodeId",
        connectFromField: "nodeId",
        connectToField: "parentId",
        depthField: "depth",
        as: "children"
    }}
]);

This should let you fetch the whole hierarchy in one go, so next, you need to calculate the tree in your application, from the information you will have in the "children" array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...