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 to update a MongoDB document without overwriting the existing one?
To update only a field value in MongoDB, use update() along with $set. This won't overwrite the existing document but only modifies the specified fields.
Syntax
db.collection.update(
{ "field": "matchValue" },
{ $set: { "fieldToUpdate": "newValue" } }
);
Sample Data
Let us first create a collection with documents ?
db.demo401.insertOne({
"_id": 1001,
"Name": "Chris",
"SubjectName": "MongoDB",
"Score": 45
});
{ "acknowledged": true, "insertedId": 1001 }
Example
Display all documents from the collection ?
db.demo401.find();
{ "_id": 1001, "Name": "Chris", "SubjectName": "MongoDB", "Score": 45 }
Update the Score field without overwriting other fields ?
db.demo401.update(
{ "_id": 1001 },
{ $set: { "Score": 89 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display the updated document ?
db.demo401.find();
{ "_id": 1001, "Name": "Chris", "SubjectName": "MongoDB", "Score": 89 }
Key Points
- The
$setoperator updates only the specified fields, leaving other fields unchanged. - Without
$set, the update operation would replace the entire document. - Use
updateOne()orupdateMany()for modern MongoDB applications.
Conclusion
The $set operator with update() allows selective field updates without overwriting the entire document. This preserves existing data while modifying only the target fields.
Advertisements
