Display a value with $addToSet in MongoDB with no duplicate elements?

The $addToSet operator in MongoDB ensures that duplicate elements are not added to an array field. When used with aggregation pipeline, it creates a set of unique values from the specified field.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: null,
            fieldName: { $addToSet: "$arrayField" }
        }
    }
]);

Sample Data

Let us create a collection with array documents ?

db.getDistinctDemo.insertMany([
    { "Values": [100, 200] },
    { "Values": [300, 100] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cef69f9ef71edecf6a1f69d"),
        ObjectId("5cef6a07ef71edecf6a1f69e")
    ]
}

Display all documents from the collection ?

db.getDistinctDemo.find();
{
    "_id": ObjectId("5cef69f9ef71edecf6a1f69d"),
    "Values": [100, 200]
}
{
    "_id": ObjectId("5cef6a07ef71edecf6a1f69e"),
    "Values": [300, 100]
}

Example: Get Distinct Array Values

Use $addToSet to collect unique array values without duplicates ?

db.getDistinctDemo.aggregate([
    {
        $group: {
            _id: 0,
            MyValues: { $addToSet: "$Values" }
        }
    }
]);
{ "_id": 0, "MyValues": [ [300, 100], [100, 200] ] }

Key Points

  • $addToSet treats each complete array [100, 200] as a single element
  • Arrays [100, 200] and [300, 100] are considered different, so both are included
  • If two documents had identical arrays, only one would appear in the result

Conclusion

The $addToSet operator creates a collection of unique values from array fields. It prevents duplicate arrays from being added to the result set, ensuring each distinct array appears only once.

Updated on: 2026-03-15T01:36:41+05:30

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements