Home > front end >  MongoDB tree structure using $graphLookup spanning multiple collections
MongoDB tree structure using $graphLookup spanning multiple collections

Time:02-15

I'm starting out with MongoDB and I'm trying to build a tree structure of objects stored in different collections. I know how many levels the hierarchy runs deep, so recursion is not a problem.

Each level of the tree is stored in a different collection (for reasons out of my control), so I have to start from Collection_A, getting all children in Collection_B, then getting all children of elements from Collection_B in Collection_C. Each item in Collection_B has the _id of its parent from Collection_A, each item in Collection_C has the $_id of its parent from Collection_B.
Also, each item has only one parent, but can have zero, one or many children.

How can I get all children and grandchildren of an element in Collection_A?
I know how to use $graphLookup to get children in Collection_B, but how do I go deeper? I think my problem is referencing the $_id field for each element in the array of children.

Here is a link to mongoplayground with the basic structure of my collections and what I tried to do.

EDIT: with help from @Hussam I got a bit further, but I realize my post was not clear enough.

This is what I'm trying to achieve:

[
  {
    "_id": 1,
    "key_A": "value_a1"
    "children_A": [
      {
        "_id": 11,
        "id_A": 1,
        "key_B": "value_b2",
        "children_B": [
          {
            "_id": 103,
            "id_B": 11,
            "key_C": "value_c4"
          },
          {
            "_id": 102,
            "id_B": 11,
            "key_C": "value_c3"
          }
        ]
      },
      {
        "_id": 10,
        "id_A": 1,
        "key_B": "value_b1",
        "children_B": [
          {
            "_id": 101,
            "id_B": 10,
            "key_C": "value_c2"
          },
          {
            "_id": 100,
            "id_B": 10,
            "key_C": "value_c1"
          }
        ]
      }
    ]
  }
]

CodePudding user response:

You had some mistake in your existing pipeline. Your startWith in second stage was not a variable.

https://mongoplayground.net/p/uIWP_mk75xm

In response to your edit, heres what you need to do to put it inside collection A objects

https://mongoplayground.net/p/tl8yWeTM26i

  • Related