How to add an extra field in a sub document in MongoDB?

To add an extra field to a subdocument in MongoDB, use the $set operator with dot notation to target specific elements within an array. Use the array index to specify which subdocument to update.

Syntax

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

Sample Data

db.addExtraFieldDemo.insertOne({
    "_id": 1,
    "UserName": "Larry",
    "UserOtherDetails": [
        {
            "UserCountryName": "US",
            "UserAge": 23
        },
        {
            "UserCountryName": "UK",
            "UserAge": 24
        }
    ]
});
{ "acknowledged": true, "insertedId": 1 }

Let us display the current document structure ?

db.addExtraFieldDemo.find().pretty();
{
    "_id": 1,
    "UserName": "Larry",
    "UserOtherDetails": [
        {
            "UserCountryName": "US",
            "UserAge": 23
        },
        {
            "UserCountryName": "UK",
            "UserAge": 24
        }
    ]
}

Example: Adding Field to First Subdocument

Add an isMarried field to the first subdocument (index 0) ?

db.addExtraFieldDemo.update(
    { "_id": 1 },
    { "$set": { "UserOtherDetails.0.isMarried": true } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify the updated document ?

db.addExtraFieldDemo.find().pretty();
{
    "_id": 1,
    "UserName": "Larry",
    "UserOtherDetails": [
        {
            "UserCountryName": "US",
            "UserAge": 23,
            "isMarried": true
        },
        {
            "UserCountryName": "UK",
            "UserAge": 24
        }
    ]
}

Key Points

  • Use dot notation with array index: "arrayField.index.newField"
  • The $set operator adds new fields or updates existing ones
  • Array indices start from 0 (first element is index 0)

Conclusion

Use $set with dot notation and array indices to add fields to specific subdocuments. This approach allows precise targeting of array elements without affecting other subdocuments in the same array.

Updated on: 2026-03-15T01:31:00+05:30

615 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements