Update a MongoDB document with Student Id and Name

To update a MongoDB document with Student Id and Name, use the update() method with $set operator. The $set operator modifies specific fields without affecting other document properties.

Syntax

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

Sample Data

Let us create a collection with student documents :

db.demo427.insertMany([
    { "StudentId": 101, "StudentName": "Chris Brown" },
    { "StudentId": 102, "StudentName": "David Miller" },
    { "StudentId": 103, "StudentName": "John Smith" },
    { "StudentId": 104, "StudentName": "Carol Taylor" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e75e711bbc41e36cc3cae75"),
        ObjectId("5e75e71abbc41e36cc3cae76"),
        ObjectId("5e75e725bbc41e36cc3cae77"),
        ObjectId("5e75e733bbc41e36cc3cae78")
    ]
}

Display all documents from the collection :

db.demo427.find();
{ "_id": ObjectId("5e75e711bbc41e36cc3cae75"), "StudentId": 101, "StudentName": "Chris Brown" }
{ "_id": ObjectId("5e75e71abbc41e36cc3cae76"), "StudentId": 102, "StudentName": "David Miller" }
{ "_id": ObjectId("5e75e725bbc41e36cc3cae77"), "StudentId": 103, "StudentName": "John Smith" }
{ "_id": ObjectId("5e75e733bbc41e36cc3cae78"), "StudentId": 104, "StudentName": "Carol Taylor" }

Example: Update Student Name by Student ID

Update the student name for StudentId 102 from "David Miller" to "John Doe" :

db.demo427.update(
    { "StudentId": 102 },
    { $set: { "StudentName": "John Doe" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display all documents to verify the update :

db.demo427.find();
{ "_id": ObjectId("5e75e711bbc41e36cc3cae75"), "StudentId": 101, "StudentName": "Chris Brown" }
{ "_id": ObjectId("5e75e71abbc41e36cc3cae76"), "StudentId": 102, "StudentName": "John Doe" }
{ "_id": ObjectId("5e75e725bbc41e36cc3cae77"), "StudentId": 103, "StudentName": "John Smith" }
{ "_id": ObjectId("5e75e733bbc41e36cc3cae78"), "StudentId": 104, "StudentName": "Carol Taylor" }

Conclusion

Use update() with $set to modify specific fields in MongoDB documents. The query condition identifies the target document, while $set updates only the specified fields, leaving other document properties unchanged.

Updated on: 2026-03-15T02:56:53+05:30

614 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements