2

I want unspecified number of nested arrays output from graph lookup aggregation.

I have data collection:

 [
        { _id: 1, name: 'AA' },
        { _id: 2, name: 'BB', parent: 1, ancestors: [1] },
        { _id: 3, name: 'CC' },
        { _id: 4, name: 'DD', parent: 3, ancestors: [3] },
        { _id: 5, name: 'DD', parent: 4, ancestors: [3, 4] },
        { _id: 6, name: 'FF', parent: 5, ancestors: [3, 4, 5] }
        ...,
        ...,
        ... ]

How to graph Lookup aggregate to output generates the unspecified hierarchy like this:

{
    "_id" : 3,
    "name" : "CC",
    "children" : [
        {
            "_id" : 4,
            "name" : "DD",
            "parent" : 3,
            "ancestors" : [
                3
            ],
          "children":[
             {
                  "_id" : 5,
                  "name" : "DD",
                  "parent" : 4,
                   "ancestors" : [
                     3,
                     4
                   ],
                 children:[
                   {
                     ...,
                     children:[...]
                    }
                 ]
                 },
           ]
        },  
    ]
}*

I hope anyone help me, thanks.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
setha va
  • 51
  • 1
  • 1
  • 3
  • people will help if you have tried something and stuck while doing it. welcome to SO , please read [mcve], please provide what code you have tried so far? what errors you getting ? – Dev Jul 13 '19 at 06:45
  • 1
    Unfortunately you cant really do this just in mongo (unless we have several strong assumptions that can simplify the problem i.e no "endless loops"). Otherwise you're going to have to combined some code. not sure about your runtime "needs" but the easiest way is to just bruteforce the problem, start with [$graphLookup](https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/) to find all the "immediate" children (depth 1), then you can just iterate over the entire array updating the subdocuments with each iteration (assuming there's no endless loops). – Tom Slabbaert Jul 14 '19 at 08:02

0 Answers0