How to find and modify a value in a nested array?

To find and modify a value in a nested array, use the $elemMatch operator to locate the array element and the $ positional operator with $set to update the specific field value.

Syntax

db.collection.update(
    { arrayName: { $elemMatch: { field: "matchValue" } } },
    { $set: { "arrayName.$.targetField": "newValue" } }
);

Sample Data

db.findAndModifyAValueInNestedArrayDemo.insertOne({
    "CompanyName": "Amazon",
    "DeveloperDetails": [
        {
            "ProjectName": "Online Book Store",
            "TeamSize": "5"
        },
        {
            "ProjectName": "Library Management System",
            "TeamSize": "7"
        },
        {
            "ProjectName": "Online Banking Application",
            "TeamSize": "15"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5ca275226304881c5ce84b9f")
}

Example: Update TeamSize in Nested Array

Let's modify the TeamSize to 20 for the project "Online Banking Application" ?

db.findAndModifyAValueInNestedArrayDemo.update(
    { DeveloperDetails: { $elemMatch: { ProjectName: "Online Banking Application" } } },
    { $set: { "DeveloperDetails.$.TeamSize": "20" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.findAndModifyAValueInNestedArrayDemo.find().pretty();
{
    "_id": ObjectId("5ca275226304881c5ce84b9f"),
    "CompanyName": "Amazon",
    "DeveloperDetails": [
        {
            "ProjectName": "Online Book Store",
            "TeamSize": "5"
        },
        {
            "ProjectName": "Library Management System",
            "TeamSize": "7"
        },
        {
            "ProjectName": "Online Banking Application",
            "TeamSize": "20"
        }
    ]
}

Key Points

  • $elemMatch matches the first array element that satisfies the query condition
  • $ positional operator references the matched array element for updates
  • Use dot notation with $ to target specific fields within the matched element

Conclusion

The combination of $elemMatch and $ positional operator provides an efficient way to find and modify specific values in nested arrays. This approach updates only the first matching element in the array.

Updated on: 2026-03-15T00:43:58+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements