Getting unique values within two arrays in one MongoDB document

To get unique values within two arrays in a MongoDB document, use the $setUnion operator in the aggregation pipeline. The $setUnion takes two or more arrays and returns an array containing the unique elements that appear in any input array.

Syntax

db.collection.aggregate([
    {
        $project: {
            uniqueArray: { $setUnion: ["$array1", "$array2"] }
        }
    }
])

Sample Data

Let us create a collection with documents ?

db.demo608.insertOne({
    "ListOfName1": ["John", "Chris", "Bob", "David"],
    "ListOfName2": ["Bob", "Sam", "John", "Robert", "Chris"]
})
{
    "acknowledged": true,
    "insertedId": ObjectId("5e974542f57d0dc0b182d62b")
}

Display all documents from the collection ?

db.demo608.find().pretty()
{
    "_id": ObjectId("5e974542f57d0dc0b182d62b"),
    "ListOfName1": [
        "John",
        "Chris",
        "Bob",
        "David"
    ],
    "ListOfName2": [
        "Bob",
        "Sam",
        "John",
        "Robert",
        "Chris"
    ]
}

Example: Getting Unique Values

Use the aggregation pipeline to get unique values within two arrays ?

db.demo608.aggregate([
    {
        $project: {
            SetOfNames: { $setUnion: ["$ListOfName1", "$ListOfName2"] }
        }
    }
]).pretty()
{
    "_id": ObjectId("5e974542f57d0dc0b182d62b"),
    "SetOfNames": [
        "Bob",
        "Chris",
        "David",
        "John",
        "Robert",
        "Sam"
    ]
}

Key Points

  • $setUnion automatically removes duplicates from the combined arrays
  • The result array is sorted in ascending order
  • Works with any number of arrays, not just two

Conclusion

The $setUnion operator efficiently combines multiple arrays while automatically removing duplicates. This provides a clean way to get unique values from multiple array fields within a single MongoDB document.

Updated on: 2026-03-15T03:49:30+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements