Updating MongoDB collection for _id?

To update a document in MongoDB using its _id field, use the $set operator within an update operation. The _id field serves as the unique identifier for each document in a collection.

Syntax

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

Sample Data

Let us create a collection with sample documents ?

db.demo741.insertMany([
    { SubjectName: "MySQL" },
    { SubjectName: "C" },
    { SubjectName: "Java" }
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5ead718657bb72a10bcf0672"),
        ObjectId("5ead718957bb72a10bcf0673"),
        ObjectId("5ead718e57bb72a10bcf0674")
    ]
}

Display all documents from the collection ?

db.demo741.find();
{ "_id" : ObjectId("5ead718657bb72a10bcf0672"), "SubjectName" : "MySQL" }
{ "_id" : ObjectId("5ead718957bb72a10bcf0673"), "SubjectName" : "C" }
{ "_id" : ObjectId("5ead718e57bb72a10bcf0674"), "SubjectName" : "Java" }

Example: Update Document by _id

Update the document with _id "5ead718957bb72a10bcf0673" to change SubjectName to "PL/SQL" ?

db.demo741.update(
    { _id: ObjectId("5ead718957bb72a10bcf0673") },
    { $set: { SubjectName: "PL/SQL" } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Verify Result

Display all documents to confirm the update ?

db.demo741.find();
{ "_id" : ObjectId("5ead718657bb72a10bcf0672"), "SubjectName" : "MySQL" }
{ "_id" : ObjectId("5ead718957bb72a10bcf0673"), "SubjectName" : "PL/SQL" }
{ "_id" : ObjectId("5ead718e57bb72a10bcf0674"), "SubjectName" : "Java" }

Conclusion

Use the _id field in the query filter with $set to update specific documents. Since _id is unique, this approach ensures you modify exactly one document with precision and efficiency.

Updated on: 2026-03-15T03:54:07+05:30

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements