Search code examples
mongodbaggregation-frameworkparent-childhierarchical-datachildren

Aggregating nested children ids by parentId in MongoDB


There is parent-child structure like this:

folder-structure

The collection:

[
  {
    "_id": "1",
    "name": "document1",
    "parentId": null
  },
  {
    "_id": "2",
    "name": "folder1",
    "parentId": null,
    
  },
  {
    "_id": "3",
    "name": "folder2",
    "parentId": "2",
    
  },
  {
    "_id": "4"
    "name": "document2",
    "parentId": "2",
    
  },
  {
    "_id": "5"
    "name": "document3",
    "parentId": "3",
    
  }
]

The goal is to get folders with contentIds array in every folder, containing only direct children ids. The response should look like:

[
  {
    "_id": "2",
    "name": "folder1",
    "parentId": null,
    "contentIds": ["3", "4"]
    
  },
  {
    "_id": "3",
    "name": "folder2",
    "parentId": "2",
    "contentIds": ["5"]
    
  }
]

Solution

  • Just perform a self lookup and a $map to get your desired format of data.

    db.collection.aggregate([
      {
        "$match": {
          name: {
            $regex: "folder"
          }
        }
      },
      {
        "$lookup": {
          "from": "collection",
          "localField": "_id",
          "foreignField": "parentId",
          "as": "contentIds"
        }
      },
      {
        "$addFields": {
          "contentIds": {
            "$map": {
              "input": "$contentIds",
              "in": "$$this._id"
            }
          }
        }
      }
    ])
    

    Here is the Mongo playground for your reference.