Search code examples
mongodbaggregation-frameworkaggregate

Create a recursive Json object from categories to display on the website menu


I created a categories document in MongoDB like this

{
    id: 1,
    name: 'digital',
    parent: null
},
{
    id: 3,
    name: 'tv',
    parent: 1
},
{
    id: 4,
    name: 'samsung',
    parent: 3
},
{
    id: 2,
    name: 'kitchen',
    parent: null
},
{
    id: 5,
    name: 'electronic',
    parent: 2
}

While thanking the forum, I had a request, a aggregate command to reach this Json

[
  {
    "id": 1,
    "name": "digital",
    "children":[
      {
        "id": 3
        "name": "tv",
        "children": [
          {
            "id": 4,
            "name": "samsung",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "id": 2,
    "name": "kitchen",
    "children": [
      {
        "id": 5,
        "name": "electronic",
        "children": []
      }
    ]
  }
]

In all records, the children field needs to be identified. I will be very grateful for your answers.


Solution

  • I get the desired result using the code:

    parents = list(database.appdatabase[database.categories_collection].find({"parent": None}, {"_id": 0}))
    response = []
    def children(parent_id):
        resp = []
        data = list(database.appdatabase[database.categories_collection].find(
            {"parent": parent_id}, {"_id": 0}
        ))
        for i in data:
            child = children(i["id"])
            if child:
                i["children"] = child
            resp.append(i)
        return resp
    
    
    for i in parents:
        child = children(i["id"])
        if child:
            i["children"] = child
        response.append(i)
    print(response) ## response = this is the answer you want