Merge two array fields in MongoDB?

To merge two array fields in MongoDB, use the $setUnion operator in an aggregation pipeline. This operator combines arrays and automatically removes duplicates while preserving unique values from both arrays.

Syntax

db.collection.aggregate([
    {
        $project: {
            "MergedFieldName": {
                $setUnion: ["$arrayField1", "$arrayField2"]
            }
        }
    }
]);

Sample Data

db.mergeTwoArrayFieldDemo.insertOne({
    "NaturalNumbers": [1, 2, 3, 8, 10, 20, 30],
    "WholeNumbers": [0, 1, 2, 63, 78, 20, 45]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd68e4057806ebf1256f11d")
}

Display the inserted document ?

db.mergeTwoArrayFieldDemo.find().pretty();
{
    "_id": ObjectId("5cd68e4057806ebf1256f11d"),
    "NaturalNumbers": [1, 2, 3, 8, 10, 20, 30],
    "WholeNumbers": [0, 1, 2, 63, 78, 20, 45]
}

Example: Merge Two Arrays

Merge the NaturalNumbers and WholeNumbers arrays into a single array ?

db.mergeTwoArrayFieldDemo.aggregate([
    {
        $project: {
            "MergedArray": {
                $setUnion: ["$NaturalNumbers", "$WholeNumbers"]
            }
        }
    }
]);
{
    "_id": ObjectId("5cd68e4057806ebf1256f11d"),
    "MergedArray": [0, 1, 2, 3, 8, 10, 20, 30, 45, 63, 78]
}

Key Points

  • $setUnion automatically removes duplicates (notice 1, 2, and 20 appear only once in the result).
  • The resulting array is sorted in ascending order.
  • Both original fields are preserved unless you specify otherwise in the projection.

Conclusion

Use $setUnion in an aggregation pipeline to merge array fields while eliminating duplicates. This operator is ideal when you need a clean, unified array from multiple sources.

Updated on: 2026-03-15T01:15:51+05:30

760 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements