Search code examples
mongodbaggregation

MongoDB: How to merge all documents into a single document in an aggregation pipeline


I have the current aggregation output as follows:

[
    {
        "courseCount": 14
    },
    {
        "registeredStudentsCount": 1
    }
]

The array has two documents. I would like to combine all the documents into a single document having all the fields in mongoDB


Solution

  •  db.collection.aggregate([
     {
       $group: {
        _id: 0,
         merged: {
        $push: "$$ROOT"
       }
       }
      },
     {
      $replaceRoot: {
      newRoot: {
        "$mergeObjects": "$merged"
       }
      }
     }
    ])
    

    Explained:

    1. Group the output documents in one field with push
    2. Replace the document root with the merged objects

    Plyaground