Graphlookup to fetch a tree structure

I have a tree structure.

node collection.

{
_id: ‘123’,
}
{
_id: ‘444’,
}
{
_id: ‘555’,
}
{
_id: ‘666’,
}

hierarchy collection.

{
_id: ‘333’,
parent: ‘123’,
child: ‘444’,
}
{
_id: ‘344’,
parent: ‘123’,
child: ‘555’,
}
{
_id: ‘344’,
parent: ‘555’,
child: ‘666’,
}

Something similar to the above. Now i need to recursively fetch the entire tree.
I want the result to be a single nested json.

{
 _id: '123',
 subTasks: [
      {
        _id: '444',
     },
     {
        _id: '555',
        subTasks: [
            {
              _id: '666',
            }
         ]
   }
 ]
 }

I tried using graph lookup. But i’m not getting the desired result

{
  from: 'hierarchies',
  startWith: '$_id' ,
  connectFromField: 'parent',
  connectToField: 'child',
  as: 'subTasks',
  maxDepth: 3,
}

Do you want to stack all parents of a child? Or all children or a parent? Just the syntax will change.

This query for example, finds all the parents of process 444.

Given the root id of the tree. I need to fetch the entire tree(ie. stack all the children).

- Root node 1
    - Child 1.1
        - Subchild 1.1.1
    - Child 1.2
- Root node 2

I don’t need the hierarchy collection’s data to be in the result. I need the nodes to be stacked.

I don’t think that’s possible.

You can the devs forum or maybe wait for another reply.

1 Like

@Santiago_Miranda I thought so too! Thanks anyway :slight_smile:

Hi @Ashwin_Ramamurthy,

We have a great community forum where you can have an in-depth conversation about specific use cases and interesting problems that you get to solve using MongoDB.

Thanks,
Sonali

2 Likes