Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to update a MongoDB row with only the objectid
To update a MongoDB document using only its ObjectId, use the update() method with the _id field as the query filter and the $set operator to modify specific fields.
Syntax
db.collection.update(
{ "_id": ObjectId("objectid_value") },
{ $set: { "field1": "new_value1", "field2": "new_value2" } }
);
Sample Data
Let us create a collection with sample documents ?
db.demo34.insertMany([
{ "StudentFirstName": "Chris", "StudentAge": 24 },
{ "StudentFirstName": "David", "StudentAge": 23 },
{ "StudentFirstName": "Bob", "StudentAge": 20 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e1758b4cfb11e5c34d898cd"),
ObjectId("5e1758bdcfb11e5c34d898ce"),
ObjectId("5e1758c6cfb11e5c34d898cf")
]
}
Display all documents from the collection ?
db.demo34.find();
{ "_id": ObjectId("5e1758b4cfb11e5c34d898cd"), "StudentFirstName": "Chris", "StudentAge": 24 }
{ "_id": ObjectId("5e1758bdcfb11e5c34d898ce"), "StudentFirstName": "David", "StudentAge": 23 }
{ "_id": ObjectId("5e1758c6cfb11e5c34d898cf"), "StudentFirstName": "Bob", "StudentAge": 20 }
Example: Update Document by ObjectId
Update the document with ObjectId 5e1758bdcfb11e5c34d898ce to change David's name to Mike and age to 19 ?
db.demo34.update(
{ "_id": ObjectId("5e1758bdcfb11e5c34d898ce") },
{ $set: { "StudentFirstName": "Mike", "StudentAge": 19 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify the Update
Display all documents to confirm the update ?
db.demo34.find();
{ "_id": ObjectId("5e1758b4cfb11e5c34d898cd"), "StudentFirstName": "Chris", "StudentAge": 24 }
{ "_id": ObjectId("5e1758bdcfb11e5c34d898ce"), "StudentFirstName": "Mike", "StudentAge": 19 }
{ "_id": ObjectId("5e1758c6cfb11e5c34d898cf"), "StudentFirstName": "Bob", "StudentAge": 20 }
Key Points
- The
_idfield is unique and provides the most efficient way to update a specific document. - Use
ObjectId("string")to convert the string representation to a proper ObjectId. - The
$setoperator updates only the specified fields, leaving other fields unchanged.
Conclusion
Using the ObjectId with the update() method provides precise document targeting in MongoDB. The _id field ensures you update exactly the intended document without affecting others.
Advertisements
