Implement MongoDB $addToSet for an array in an array and append a value

To implement MongoDB $addToSet for an array within an array and append a value, use the update() method with dot notation to target the specific nested array. The $addToSet operator adds a value to an array only if it doesn't already exist, preventing duplicates.

Syntax

db.collection.update(
    {query},
    { $addToSet: { "parentArray.index.nestedArray": value } }
);

Sample Data

db.demo509.insertOne({
    "value1": [
        {
            "value2": [76, 14, 56]
        },
        {
            "value2": [12, 19, 91]
        },
        {
            "value2": [87]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e88421d987b6e0e9d18f57d")
}

Verify Initial Data

db.demo509.find();
{
    "_id": ObjectId("5e88421d987b6e0e9d18f57d"),
    "value1": [
        { "value2": [76, 14, 56] },
        { "value2": [12, 19, 91] },
        { "value2": [87] }
    ]
}

Example: Add Value to Third Nested Array

Add value 1000 to the third element's value2 array (index 2) ?

db.demo509.update(
    {},
    { $addToSet: { "value1.2.value2": 1000 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo509.find();
{
    "_id": ObjectId("5e88421d987b6e0e9d18f57d"),
    "value1": [
        { "value2": [76, 14, 56] },
        { "value2": [12, 19, 91] },
        { "value2": [87, 1000] }
    ]
}

Key Points

  • Use dot notation "parentArray.index.nestedArray" to target specific nested arrays.
  • $addToSet prevents duplicate values automatically.
  • Array indices are zero-based (0, 1, 2, etc.).

Conclusion

The $addToSet operator with dot notation efficiently adds unique values to nested arrays. It combines array targeting with duplicate prevention, making it ideal for maintaining clean nested array data.

Updated on: 2026-03-15T03:20:33+05:30

428 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements