Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

644
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!