6

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?

Wan B.
  • 18,367
  • 4
  • 54
  • 71
mmu36478
  • 1,295
  • 4
  • 19
  • 40

1 Answers1

13

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.

Wan B.
  • 18,367
  • 4
  • 54
  • 71