How to represent the data in tree structure

Hi

we have a requirement to show data in tree format.

Sample Data:

db.FamilyTree.insert({"id":"100", "ParentName":"Jhon Smith", "Children" : "Michael Smith" })
db.FamilyTree.insert({"id":"100", "Diana Smith":"Jhon Smith", "Children" : "Diana Smith"})
db.FamilyTree.insert({"id":"101", "ParentName":"Michael Smith", "Children" : ""})
db.FamilyTree.insert({"id":"102", "ParentName":"Diana Smith", "Children" : "Britney Smith"})
db.FamilyTree.insert({"id":"301", "ParentName":"Britney Smith", "Children" : ""})
db.FamilyTree.insert({"id":"200", "ParentName":"Richard Smith", "Children" : "M Smith" })
db.FamilyTree.insert({"id":"200", "ParentName":"Richard Smith", "Children" : "D Smith" })
db.FamilyTree.insert({"id":"201", "ParentName":"M Smith", "Children" : "" })
db.FamilyTree.insert({"id":"202", "ParentName":"D Smith", "Children" : "" })

the expected output should be in the below format.

  [
   {
      "id":"100",
      "name":"Jhon Smith",
      "children":[
         {
            "id":"101",
            "name":"Michael Smith",
            "children":null
         },
         {
            "id":"102",
            "name":"Diana Smith",
            "children":[
               {
                  "id":"301",
                  "name":"Britney Smith",
                  "children":null
               }
            ]
         }
      ]
   },
   {
      "id":"200",
      "name":"Richard Smith",
      "children":[
         {
            "id":101,
            "name":"Michael Smith",
            "children":null
         },
         {
            "id":"102",
            "name":"Diana Smith",
            "children":null
         }
      ]
   }
]

I Have tried with $graphLookup but I didn’t get the required output:

db.FamilyTree.aggregate( [
        { $project: { _id: 0}},
   { 
      $graphLookup: {
         from: "FamilyTree",
         startWith: "$Children",
         connectFromField: "Children",
         connectToField: "ParentName",
         as: "TreeSearch"

     
      }
   }
] )

Please help me with this to achieve the required outcome.

Thanks.

Hi @vidiyala_ganesh, I would recommend you to use $group clause to merge the same type of records for that check this.

Hi @vidiyala_ganesh, and welcome to the forums!

It’s been a while since you posted this question, have you found a solution yet ?

I would recommend to change the data model. For example, the Children field should contain a list of children. For example:

db.FamilyTree.insert({"id":200, name:"Richard Smith", Children:[201, 202]})
db.FamilyTree.insert({"id":201, name:"M. Smith", Children:[]})
db.FamilyTree.insert({"id":202, name:"D. Smith", Children:[]})

Just by performing the above data remodelling, your example aggregation pipeline should provide the desire output.
For more information about modelling data in tree structures please see:

Regards,
Wan.