Unable to implement $addToSet in MongoDB to fetch values of a single field?

The $addToSet operator adds values to an array unless the value is already present, in which case $addToSet does nothing to that array. When used with $group in aggregation, it creates a unique set of values from a field across multiple documents.

Syntax

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

Sample Data

db.demo533.insertMany([
    {"ProjectName": "Online Hospital Management"},
    {"ProjectName": "Online Library Management"},
    {"ProjectName": "Online Hospital Management"},
    {"ProjectName": "Online Customer Tracker"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8b4cfaef4dcbee04fbbbfc"),
        ObjectId("5e8b4d02ef4dcbee04fbbbfd"),
        ObjectId("5e8b4d04ef4dcbee04fbbbfe"),
        ObjectId("5e8b4d0def4dcbee04fbbbff")
    ]
}

Display All Documents

db.demo533.find();
{ "_id": ObjectId("5e8b4cfaef4dcbee04fbbbfc"), "ProjectName": "Online Hospital Management" }
{ "_id": ObjectId("5e8b4d02ef4dcbee04fbbbfd"), "ProjectName": "Online Library Management" }
{ "_id": ObjectId("5e8b4d04ef4dcbee04fbbbfe"), "ProjectName": "Online Hospital Management" }
{ "_id": ObjectId("5e8b4d0def4dcbee04fbbbff"), "ProjectName": "Online Customer Tracker" }

Example: Using $addToSet to Get Unique Project Names

The following query implements $addToSet to fetch unique values of the ProjectName field ?

db.demo533.aggregate([
    {
        $group: {
            _id: null,
            SetOfProject: { $addToSet: "$ProjectName" }
        }
    }
]);
{ "_id": null, "SetOfProject": [ "Online Customer Tracker", "Online Library Management", "Online Hospital Management" ] }

How It Works

  • $group groups all documents together using _id: null
  • $addToSet collects unique values from the ProjectName field
  • Duplicate "Online Hospital Management" appears only once in the result

Conclusion

Use $addToSet with $group in aggregation pipelines to extract unique values from a field across multiple documents. This is particularly useful for removing duplicates and creating distinct value sets.

Updated on: 2026-03-15T03:29:55+05:30

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements