MongoDB aggregate to convert multiple documents into single document with an array?

MongoDB aggregation pipeline allows you to group multiple documents into single documents containing arrays. Use the $group stage with $push operator to combine documents sharing a common field into a single document with an array field.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: "$groupingField",
            arrayField: {
                $push: {
                    field1: "$field1",
                    field2: "$field2"
                }
            }
        }
    }
]);

Sample Data

db.demo248.insertMany([
    {"id": 101, "Name": "Chris", "Age": 21, "CountryName": "US"},
    {"id": 101, "Name": "Bob", "Age": 22, "CountryName": "UK"},
    {"id": 102, "Name": "Mike", "Age": 20, "CountryName": "AUS"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e46b6651627c0c63e7dba6d"),
        ObjectId("5e46b6741627c0c63e7dba6e"),
        ObjectId("5e46b6811627c0c63e7dba6f")
    ]
}

Original Documents

db.demo248.find();
{"_id": ObjectId("5e46b6651627c0c63e7dba6d"), "id": 101, "Name": "Chris", "Age": 21, "CountryName": "US"}
{"_id": ObjectId("5e46b6741627c0c63e7dba6e"), "id": 101, "Name": "Bob", "Age": 22, "CountryName": "UK"}
{"_id": ObjectId("5e46b6811627c0c63e7dba6f"), "id": 102, "Name": "Mike", "Age": 20, "CountryName": "AUS"}

Example: Group by ID Field

Convert multiple documents into single documents with array by grouping on the id field ?

db.demo248.aggregate([
    {
        $group: {
            _id: "$id",
            details: {
                $push: {
                    id: "$id",
                    Name: "$Name",
                    Age: "$Age",
                    CountryName: "$CountryName"
                }
            }
        }
    }
]);
{"_id": 102, "details": [{"id": 102, "Name": "Mike", "Age": 20, "CountryName": "AUS"}]}
{"_id": 101, "details": [{"id": 101, "Name": "Chris", "Age": 21, "CountryName": "US"}, {"id": 101, "Name": "Bob", "Age": 22, "CountryName": "UK"}]}

How It Works

  • $group stage groups documents by the _id field value
  • $push operator adds each matching document to the details array
  • Documents with id: 101 are combined into one document with two array elements
  • Document with id: 102 creates a single-element array

Conclusion

The $group stage with $push operator effectively converts multiple related documents into single documents containing arrays. This is useful for organizing data by common identifiers or creating summary documents.

Updated on: 2026-03-15T02:03:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements