Get distinct levels of array field in MongoDB?

To get distinct levels of array field in MongoDB, use the $addToSet operator within an aggregation pipeline. This operator collects unique values and prevents duplicates when grouping array fields.

Syntax

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

Sample Data

db.demo122.insertMany([
    {"ListOfValues": [100, 10]},
    {"ListOfValues": [240, 10]},
    {"ListOfValues": [100, 10]}
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": ObjectId("..."),
        "1": ObjectId("..."),
        "2": ObjectId("...")
    }
}

Display all documents from the collection ?

db.demo122.find();
{ "_id": ObjectId("5e2f20f1140daf4c2a3544b6"), "ListOfValues": [100, 10] }
{ "_id": ObjectId("5e2f20f7140daf4c2a3544b7"), "ListOfValues": [240, 10] }
{ "_id": ObjectId("5e2f20f8140daf4c2a3544b8"), "ListOfValues": [100, 10] }

Example: Get Distinct Array Values

Use aggregation with $addToSet to collect unique array values ?

db.demo122.aggregate([
    {
        $group: {
            "_id": null,
            "ListOfValues": { $addToSet: "$ListOfValues" }
        }
    }
]);
{ "_id": null, "ListOfValues": [[240, 10], [100, 10]] }

Key Points

  • $addToSet automatically eliminates duplicate array values during grouping.
  • Setting "_id": null groups all documents into a single result.
  • Each unique array combination appears only once in the final output.

Conclusion

Use $addToSet within MongoDB aggregation to collect distinct array field values. This operator ensures only unique array combinations are included in the grouped results.

Updated on: 2026-03-15T02:11:31+05:30

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements