Add a field to an embedded document in an array in MongoDB?

To add a field to an embedded document in an array in MongoDB, use the $set operator combined with the $ positional operator and $elemMatch to target the specific array element.

Syntax

db.collection.update(
    { "arrayField": { $elemMatch: { "matchField": "value" } } },
    { $set: { "arrayField.$.newField": "newValue" } }
);

Sample Data

Let us create a collection with documents ?

db.addAFieldDemo.insertOne({
    "ClientName": "Larry",
    "ClientCountryName": "US",
    "ClientOtherDetails": [
        {
            "ClientProjectName": "Online Banking System"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd44bdc2cba06f46efe9ee8")
}

Display the current document ?

db.addAFieldDemo.find().pretty();
{
    "_id": ObjectId("5cd44bdc2cba06f46efe9ee8"),
    "ClientName": "Larry",
    "ClientCountryName": "US",
    "ClientOtherDetails": [
        {
            "ClientProjectName": "Online Banking System"
        }
    ]
}

Example: Add Field to Embedded Document

Add an isMarried field to the embedded document in the array ?

db.addAFieldDemo.update(
    { "ClientOtherDetails": { $elemMatch: { "ClientProjectName": "Online Banking System" } } },
    { $set: { "ClientOtherDetails.$.isMarried": true } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display the updated document ?

db.addAFieldDemo.find().pretty();
{
    "_id": ObjectId("5cd44bdc2cba06f46efe9ee8"),
    "ClientName": "Larry",
    "ClientCountryName": "US",
    "ClientOtherDetails": [
        {
            "ClientProjectName": "Online Banking System",
            "isMarried": true
        }
    ]
}

Key Points

  • $elemMatch locates the array element matching the specified criteria.
  • $ positional operator identifies the matched array element's position.
  • $set adds the new field to the targeted embedded document.

Conclusion

Use $elemMatch with the $ positional operator to precisely target and add fields to specific embedded documents within arrays. This approach ensures only the matching array element is modified.

Updated on: 2026-03-15T01:11:29+05:30

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements