Is it possible to utilize $addToSet multiple times in the same update?

Yes, it is possible to use $addToSet multiple times in the same update operation. You can specify multiple fields or use the $each modifier to add multiple values to the same array in a single operation.

Syntax

// Multiple $addToSet operations
db.collection.update(
    { query },
    {
        $addToSet: {
            "field1": "value1",
            "field2": "value2"
        }
    }
);

// Adding multiple values to same array
db.collection.update(
    { query },
    {
        $addToSet: {
            "arrayField": { $each: ["value1", "value2", "value3"] }
        }
    }
);

Sample Data

db.demo27.insertMany([
    {"StudentDetails": {"101": {"Subject": ["Java"]}}},
    {"StudentDetails": {"101": {"Subject": ["MySQL"]}}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e15f9e822d07d3b95082e7f"),
        ObjectId("5e15f9eb22d07d3b95082e80")
    ]
}

Initial Data

db.demo27.find().pretty();
{
    "_id": ObjectId("5e15f9e822d07d3b95082e7f"),
    "StudentDetails": {
        "101": {
            "Subject": ["Java"]
        }
    }
}
{
    "_id": ObjectId("5e15f9eb22d07d3b95082e80"),
    "StudentDetails": {
        "101": {
            "Subject": ["MySQL"]
        }
    }
}

Method 1: Multiple Values with $each

Add multiple subjects to the first document using $addToSet with $each ?

db.demo27.update(
    {"StudentDetails.101.Subject": "Java"},
    {
        $addToSet: {
            "StudentDetails.101.Subject": {
                $each: ["MongoDB", "Python", "JavaScript"]
            }
        }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Method 2: Single Value Addition

Add a single subject to the second document ?

db.demo27.update(
    {"StudentDetails.101.Subject": "MySQL"},
    {
        $addToSet: {
            "StudentDetails.101.Subject": "MongoDB"
        }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Results

db.demo27.find().pretty();
{
    "_id": ObjectId("5e15f9e822d07d3b95082e7f"),
    "StudentDetails": {
        "101": {
            "Subject": ["Java", "MongoDB", "Python", "JavaScript"]
        }
    }
}
{
    "_id": ObjectId("5e15f9eb22d07d3b95082e80"),
    "StudentDetails": {
        "101": {
            "Subject": ["MySQL", "MongoDB"]
        }
    }
}

Key Points

  • $addToSet prevents duplicate values in arrays
  • Use $each modifier to add multiple values in one operation
  • Multiple $addToSet operations can target different fields simultaneously

Conclusion

MongoDB supports multiple $addToSet operations in a single update. Use the $each modifier to add multiple values efficiently while maintaining array uniqueness.

Updated on: 2026-03-15T02:39:04+05:30

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements