Update elements inside an array in MongoDB?

To update elements inside an array in MongoDB, use the $set operator combined with the $ positional operator. The positional operator identifies the array element that matches the query condition and allows you to update specific fields within that element.

Syntax

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

Create Sample Data

db.demo494.insertOne({
    "CollegeDetails": [
        {
            "CollegeName": "MIT",
            "Fees": 80000
        },
        {
            "CollegeName": "SU",
            "Fees": 90000
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e84a5c1b0f3fa88e22790c9")
}

Example: Update Fees for MIT

Update the fees for MIT from 80000 to 100000 ?

db.demo494.update(
    { "CollegeDetails.CollegeName": "MIT" },
    { $set: { "CollegeDetails.$.Fees": 100000 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo494.find().pretty();
{
    "_id": ObjectId("5e84a5c1b0f3fa88e22790c9"),
    "CollegeDetails": [
        {
            "CollegeName": "MIT",
            "Fees": 100000
        },
        {
            "CollegeName": "SU",
            "Fees": 90000
        }
    ]
}

Key Points

  • The $ operator updates the first matching array element only
  • Use dot notation to specify which field within the array element to update
  • The query condition must match a field within the array elements

Conclusion

The $set operator with the $ positional operator provides a precise way to update specific fields within array elements. This approach ensures only the matched element is modified while preserving other array elements.

Updated on: 2026-03-15T03:17:22+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements