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
How can we update a record in MongoDB?
To update a record in MongoDB, use the update() method with a query filter and update operators like $set. You can update based on _id or any field that uniquely identifies the document.
Syntax
db.collection.update(
{ "field": "value" },
{ $set: { "field": "newValue" } }
);
Create Sample Data
Let us create a collection with sample documents ?
db.demo458.insertMany([
{ _id: 101, "Name": "David" },
{ _id: 102, "Name": "Chris" },
{ _id: 103, "Name": "Bob" }
]);
{
"acknowledged": true,
"insertedIds": {
"0": 101,
"1": 102,
"2": 103
}
}
Display all documents from the collection ?
db.demo458.find();
{ "_id": 101, "Name": "David" }
{ "_id": 102, "Name": "Chris" }
{ "_id": 103, "Name": "Bob" }
Example: Update Record by _id
Update the document with _id: 102 to change the name ?
db.demo458.update(
{ _id: 102 },
{ $set: { "Name": "David Miller" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display all documents to verify the update ?
db.demo458.find();
{ "_id": 101, "Name": "David" }
{ "_id": 102, "Name": "David Miller" }
{ "_id": 103, "Name": "Bob" }
Key Points
- Use
$setoperator to update specific fields without affecting other fields. - The
_idfield provides a unique identifier for targeted updates. - The
WriteResultshows how many documents were matched and modified.
Conclusion
The update() method with $set operator allows precise field updates in MongoDB. Using _id ensures you update the exact document you intend to modify.
Advertisements
