Combining unique items from arrays in MongoDB?

To combine unique items from arrays in MongoDB, use the aggregation pipeline with $concatArrays, $setDifference, and $addToSet operators to merge array values and remove duplicates.

Syntax

db.collection.aggregate([
    {
        $project: {
            combinedArray: {
                $setDifference: [
                    { $concatArrays: ["$array1", "$array2", "$array3"] },
                    []
                ]
            }
        }
    },
    { $unwind: "$combinedArray" },
    { $group: { _id: null, uniqueItems: { $addToSet: "$combinedArray" } } }
]);

Sample Data

db.demo420.insertMany([
    {
        "details": [
            {
                "Value1": 10,
                "Value2": 20,
                "Value3": 30
            }
        ]
    },
    {
        "Info": [
            {
                "Value1": 10,
                "Value2": 20,
                "Value3": 300
            }
        ]
    }
]);
WriteResult({ "nInserted": 2 })

Example: Combining Unique Values from Object Fields

Extract and combine unique values from nested object fields ?

db.demo420.aggregate([
    {
        "$project": {
            "_id": 0,
            "unique": {
                "$filter": {
                    "input": {
                        "$setDifference": [
                            {
                                "$concatArrays": [
                                    "$Info.Value1",
                                    "$Info.Value2",
                                    "$Info.Value3"
                                ]
                            },
                            []
                        ]
                    },
                    "cond": { "$ne": [ "$$this", "" ] }
                }
            }
        }
    },
    { "$unwind": "$unique" },
    {
        "$group": {
            "_id": null,
            "uniqueArray": { "$addToSet": "$unique" }
        }
    }
]);
{ "_id": null, "uniqueArray": [ 300, 20, 10 ] }

How It Works

  • $concatArrays merges multiple arrays into a single array
  • $setDifference removes null/empty values by comparing with an empty array
  • $filter excludes empty strings and unwanted values
  • $unwind deconstructs the array into individual documents
  • $addToSet collects unique values, automatically removing duplicates

Conclusion

Use MongoDB's aggregation pipeline with $concatArrays and $addToSet to combine arrays and automatically extract unique values. The $setDifference and $filter operators help clean unwanted elements from the result.

Updated on: 2026-03-15T02:55:33+05:30

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements