Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query tree structure recursively with MongoDB?

For example a tree structure as;

[
    {id: 1 , childrenIdList: [2, 3]},
    {id: 2 , childrenIdList: [4, 5]},
    {id: 3 , childrenIdList: []},
    {id: 4 , childrenIdList: [6, 7]},
    {id: 5 , childrenIdList: []},
    {id: 6 , childrenIdList: []},
    {id: 7 , childrenIdList: []}
]

which is like;

               1
          2        3
       4    5
    6    7

How can I trace tree from starting the leaf node(id=7) to root(id=1)?

Finding the parent of id=7 is easy as;

db.document.find({childrenList: { $in: [7]}}, {id: 1}).toArray(function(err), result{
  /*result gives 
  {"id" : NumberInt(4)}
  now I should look the parent of id=4, and parent of id=2 as you know.
  */
})

Is recursive queries possible on mongodb? How can I implement it?

like image 764
mmu36478 Avatar asked Jan 09 '17 06:01

mmu36478


People also ask

What is the use of tree data structure in MongoDB?

MongoDB allows various ways to use tree data structures to model large hierarchical or nested data relationships. Model Tree Structures with Parent References Presents a data model that organizes documents in a tree-like structure by storing referencesto "parent" nodes in "child" nodes.

Is recursive queries possible on MongoDB?

Is recursive queries possible on mongodb? How can I implement it? Depending on your use case, MongoDB v3.4 provides an aggregation pipeline operator called $graphLookup. The aggregation operator is able to perform a recursive search on a collection. See more definiton on $graphLookup definition.

How to model large hierarchical or nested data relationships in MongoDB?

MongoDB allows various ways to use tree data structures to model large hierarchical or nested data relationships. Model Tree Structures with Parent References Presents a data model that organizes documents in a tree-like structure by storing referencesto "parent" nodes in "child" nodes. Model Tree Structures with Child References

How to get the descendants of a node in MongoDB?

There are two options to get all node descendants. One is a classic approach through recursion: The other is to use an aggregation framework introduced in MongoDB 2.2: For each node, we'll store the ID and PathToNode


1 Answers

Depending on your use case, MongoDB v3.4 provides an aggregation pipeline operator called $graphLookup. The aggregation operator is able to perform a recursive search on a collection. See more definiton on $graphLookup definition.

Using your documents hierarchy and values above as examples, you could try running below aggregation:

db.collectionName.aggregate([

                {$unwind:{
                        path:"$childrenIdList", 
                        preserveNullAndEmptyArrays: true}
                  }, 
                {$graphLookup:{
                        from:"collectionName", 
                        startWith:"$_id", 
                        connectFromField:"_id", 
                        connectToField:"childrenIdList", 
                        as:"myparents",  
                        restrictSearchWithMatch: {"_id"}}
                  }, 
                {$match: {"_id": 7 } },
                {$group:{
                        _id:"$_id", 
                        parents:{$addToSet:"$myparents._id"}
                  }}
]);

The above should return result as below:

{ "_id" : 7, "parents" : [ [ 1, 2, 4 ] ] }

Having said that, if you have a large collection the above query may not be performant as you'll be performing $unwind on each documents and won't be able to utilise indexes. As suggested by others, you should re-consider your document model structure. See Data Models Tree Structures. Optimise based on your application logic and querying use case, and let the flexible document schema follow.

like image 52
Wan Bachtiar Avatar answered Oct 24 '22 14:10

Wan Bachtiar