Want to update inner field in a MongoDB

To update an inner field in MongoDB, use the $set operator with dot notation to target the nested field within a document. This allows you to modify specific fields inside embedded documents without affecting other fields.

Syntax

db.collectionName.update(
    {"_id": ObjectId},
    {$set: {"outerField.innerField": newValue}}
);

Sample Data

Let us create a collection with a document containing nested fields ?

db.updateDocumentDemo.insertOne({
    "StudentDetails": {
        "StudentFirstName": "Adam",
        "StudentLastName": "Samith"
    },
    "StudentOtherDetails": {
        "StudentFavouriteSubject": "MySQL",
        "StudentScore": 45
    }
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd50bb32cba06f46efe9efe")
}

View Current Document

db.updateDocumentDemo.find().pretty();
{
    "_id": ObjectId("5cd50bb32cba06f46efe9efe"),
    "StudentDetails": {
        "StudentFirstName": "Adam",
        "StudentLastName": "Samith"
    },
    "StudentOtherDetails": {
        "StudentFavouriteSubject": "MySQL",
        "StudentScore": 45
    }
}

Update Inner Field

Update the "StudentFavouriteSubject" field from "MySQL" to "MongoDB" ?

db.updateDocumentDemo.update(
    {"_id": ObjectId("5cd50bb32cba06f46efe9efe")},
    {$set: {"StudentOtherDetails.StudentFavouriteSubject": "MongoDB"}}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.updateDocumentDemo.find().pretty();
{
    "_id": ObjectId("5cd50bb32cba06f46efe9efe"),
    "StudentDetails": {
        "StudentFirstName": "Adam",
        "StudentLastName": "Samith"
    },
    "StudentOtherDetails": {
        "StudentFavouriteSubject": "MongoDB",
        "StudentScore": 45
    }
}

Conclusion

Use dot notation with $set to update nested fields in MongoDB documents. This approach modifies only the specified inner field while preserving all other document structure and values.

Updated on: 2026-03-15T01:12:21+05:30

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements