How to merge multiple documents in MongoDB?

To merge multiple documents in MongoDB, use the aggregate() method with operators like $group and $push to combine data from documents that share common fields.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $group: {
        _id: "$groupingField",
        mergedArray: { $push: "$arrayField" },
        sumField: { $sum: "$numericField" }
    }}
]);

Sample Data

db.demo436.insertMany([
    {
        "_id": "101",
        "Name": "Chris",
        "details": [
            {
                "CountryName": "US",
                "Age": 21
            }
        ],
        "Price": 50
    },
    {
        "_id": "102",
        "Name": "Chris",
        "details": [
            {
                "CountryName": "UK",
                "Age": 22
            }
        ],
        "Price": 78
    },
    {
        "_id": "103",
        "Name": "Chris",
        "details": [
            {
                "CountryName": "US",
                "Age": 21
            }
        ],
        "Price": 50
    }
]);

Display all documents from the collection ?

db.demo436.find();
{ "_id": "101", "Name": "Chris", "details": [ { "CountryName": "US", "Age": 21 } ], "Price": 50 }
{ "_id": "102", "Name": "Chris", "details": [ { "CountryName": "UK", "Age": 22 } ], "Price": 78 }
{ "_id": "103", "Name": "Chris", "details": [ { "CountryName": "US", "Age": 21 } ], "Price": 50 }

Example: Merge Documents by Name

Merge all documents with the same Name, combining their details arrays and summing the Price ?

db.demo436.aggregate([
    { $sort: { _id: 1, Name: 1 } },
    { $unwind: "$details" },
    { $group: {
        _id: "$Name",
        details: { $push: "$details" },
        Price: { $sum: "$Price" },
        id: { $last: { $concat: ["$_id", "_", "AppendedValue"] } },
        Name: { $last: "$Name" }
    }},
    { $addFields: { Id: "NewIdAppped", _id: "$id" } },
    { $project: { "id": 0 } }
]);
{
    "_id": "103_AppendedValue",
    "details": [
        { "CountryName": "US", "Age": 21 },
        { "CountryName": "UK", "Age": 22 },
        { "CountryName": "US", "Age": 21 }
    ],
    "Price": 178,
    "Name": "Chris",
    "Id": "NewIdAppped"
}

How It Works

  • $sort − Orders documents for consistent processing
  • $unwind − Deconstructs the details array to separate documents
  • $group − Groups by Name, pushes details into array, sums Price
  • $addFields − Adds new fields and modifies the _id
  • $project − Excludes unwanted fields from output

Conclusion

Use MongoDB's aggregation pipeline with $group and $push operators to merge documents sharing common field values. The $unwind stage helps combine nested arrays from multiple documents into a single merged array.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements