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 only certain fields?
To update only certain fields in MongoDB, use the $set operator. This operator modifies specific fields without affecting other existing fields in the document.
Syntax
db.collection.update(
{ "field": "value" },
{ $set: { "fieldToUpdate": "newValue" } }
);
Sample Data
Let us create a collection with sample documents −
db.demo265.insertMany([
{"id": 101, "Name": "Chris"},
{"id": 102, "Name": "Bob"},
{"id": 103, "Name": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e480d781627c0c63e7dbaa4"),
ObjectId("5e480d7d1627c0c63e7dbaa5"),
ObjectId("5e480d841627c0c63e7dbaa6")
]
}
Display all documents from the collection −
db.demo265.find();
{ "_id": ObjectId("5e480d781627c0c63e7dbaa4"), "id": 101, "Name": "Chris" }
{ "_id": ObjectId("5e480d7d1627c0c63e7dbaa5"), "id": 102, "Name": "Bob" }
{ "_id": ObjectId("5e480d841627c0c63e7dbaa6"), "id": 103, "Name": "David" }
Example: Update Specific Field
Update only the id field for David's document −
db.demo265.update(
{"Name": "David"},
{$set: {"id": 10004}}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo265.find();
{ "_id": ObjectId("5e480d781627c0c63e7dbaa4"), "id": 101, "Name": "Chris" }
{ "_id": ObjectId("5e480d7d1627c0c63e7dbaa5"), "id": 102, "Name": "Bob" }
{ "_id": ObjectId("5e480d841627c0c63e7dbaa6"), "id": 10004, "Name": "David" }
Key Points
-
$setupdates only the specified fields, leaving other fields unchanged. - If the field doesn't exist,
$setwill create it. - Use
updateOne()for single document updates orupdateMany()for multiple documents.
Conclusion
The $set operator provides precise field-level updates without modifying the entire document. This approach ensures data integrity by preserving unchanged fields while updating only the necessary ones.
Advertisements
