Update Array element in MongoDB?

To update an array element in MongoDB, you can use various operators like $set, $addToSet, or $push combined with the positional operator $ to target specific array elements.

Syntax

db.collection.update(
    {"arrayField.elementField": "matchValue"},
    { $set: {"arrayField.$.newField": "newValue"} }
);

Sample Data

db.updateArrayDemo.insertOne({
    "ClientDetails": [
        {
            "ClientName": "John",
            "DeveloperDetails": []
        },
        {
            "ClientName": "Larry",
            "DeveloperDetails": []
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5ccf465edceb9a92e6aa1960")
}

View Current Document

db.updateArrayDemo.find().pretty();
{
    "_id": ObjectId("5ccf465edceb9a92e6aa1960"),
    "ClientDetails": [
        {
            "ClientName": "John",
            "DeveloperDetails": []
        },
        {
            "ClientName": "Larry",
            "DeveloperDetails": []
        }
    ]
}

Example: Adding New Field to Array Element

Add a Technology field to Larry's client details using $addToSet ?

db.updateArrayDemo.update(
    {"ClientDetails.ClientName": "Larry"},
    {
        $addToSet: {
            "ClientDetails.$.Technology": {
                "DeveloperName": "Chris",
                "WorkExperience": 5
            }
        }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Update

db.updateArrayDemo.find().pretty();
{
    "_id": ObjectId("5ccf465edceb9a92e6aa1960"),
    "ClientDetails": [
        {
            "ClientName": "John",
            "DeveloperDetails": []
        },
        {
            "ClientName": "Larry",
            "DeveloperDetails": [],
            "Technology": [
                {
                    "DeveloperName": "Chris",
                    "WorkExperience": 5
                }
            ]
        }
    ]
}

Key Points

  • $ positional operator identifies the first matching array element
  • $addToSet prevents duplicate values in arrays
  • $set replaces existing values, $push always adds new elements

Conclusion

Use the positional operator $ with update operators like $addToSet, $set, or $push to modify specific elements in MongoDB arrays. The $ operator targets the first array element that matches your query criteria.

Updated on: 2026-03-15T00:59:33+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements