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 selected fields
To update selected fields in MongoDB, use the update() method with the $set operator. The $set operator modifies specific fields without affecting other document properties.
Syntax
db.collection.update(
{ "field": "matchValue" },
{ $set: { "field": "newValue" } }
);
Create Sample Data
Let us create a collection with sample documents ?
db.demo352.insertMany([
{ "Name": "Chris" },
{ "Name": "David" },
{ "Name": "Bob" },
{ "Name": "Mike" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e55510af8647eb59e5620ba"),
ObjectId("5e55510ef8647eb59e5620bb"),
ObjectId("5e555112f8647eb59e5620bc"),
ObjectId("5e555115f8647eb59e5620bd")
]
}
Display all documents from the collection ?
db.demo352.find();
{ "_id": ObjectId("5e55510af8647eb59e5620ba"), "Name": "Chris" }
{ "_id": ObjectId("5e55510ef8647eb59e5620bb"), "Name": "David" }
{ "_id": ObjectId("5e555112f8647eb59e5620bc"), "Name": "Bob" }
{ "_id": ObjectId("5e555115f8647eb59e5620bd"), "Name": "Mike" }
Example: Update Selected Field
Update David's name to Robert using $set ?
db.demo352.update(
{ "Name": "David" },
{ $set: { "Name": "Robert" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display all documents to verify the update ?
db.demo352.find();
{ "_id": ObjectId("5e55510af8647eb59e5620ba"), "Name": "Chris" }
{ "_id": ObjectId("5e55510ef8647eb59e5620bb"), "Name": "Robert" }
{ "_id": ObjectId("5e555112f8647eb59e5620bc"), "Name": "Bob" }
{ "_id": ObjectId("5e555115f8647eb59e5620bd"), "Name": "Mike" }
Conclusion
The $set operator allows you to update specific fields in MongoDB documents while preserving other existing fields. Use it with update() to modify only the fields you need to change.
Advertisements
