Coalesce values from different properties into a single array with MongoDB aggregation

To coalesce values from different properties into a single array in MongoDB, use the $group stage to collect values with $addToSet, then $project with $setUnion to merge them into one unified array.

Syntax

db.collection.aggregate([
    {
        $group: {
            "_id": null,
            "property1": { $addToSet: "$field1" },
            "property2": { $addToSet: "$field2" }
        }
    },
    {
        $project: {
            "coalescedArray": { $setUnion: ["$property1", "$property2"] }
        }
    }
]);

Sample Data

db.demo244.insertMany([
    { "Value1": 10, "Value2": 20 },
    { "Value1": 20, "Value2": 30 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e4582e31627c0c63e7dba63"),
        ObjectId("5e4582f11627c0c63e7dba64")
    ]
}

Display all documents from the collection ?

db.demo244.find();
{ "_id": ObjectId("5e4582e31627c0c63e7dba63"), "Value1": 10, "Value2": 20 }
{ "_id": ObjectId("5e4582f11627c0c63e7dba64"), "Value1": 20, "Value2": 30 }

Example: Coalesce Values into Single Array

Merge all values from Value1 and Value2 properties into one unified array ?

db.demo244.aggregate([
    {
        $group: {
            "_id": null,
            "v1": { $addToSet: "$Value1" },
            "v2": { $addToSet: "$Value2" }
        }
    },
    {
        $project: {
            "AllValues": { $setUnion: ["$v1", "$v2"] }
        }
    }
]);
{ "_id": null, "AllValues": [10, 20, 30] }

How It Works

  • $group with $addToSet creates separate arrays of unique values from each property.
  • $setUnion in $project merges the arrays, removing duplicates automatically.
  • The result contains all unique values from both properties in a single array.

Conclusion

Use $group with $addToSet to collect values, then $setUnion to coalesce them into one array. This approach automatically handles duplicates and creates a unified collection of values from multiple properties.

Updated on: 2026-03-15T02:02:53+05:30

735 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements