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
Update in MongoDB and prevent overwrite?
To update a document in MongoDB without overwriting the entire document, use the $set operator to modify specific fields while preserving existing data. This prevents accidental data loss during updates.
Syntax
db.collection.update(
{ "field": "matchValue" },
{ $set: { "fieldToUpdate": "newValue" } }
);
Sample Data
db.demo601.insertMany([
{
id: 1,
userDetails: {
userName: "John",
userMailId: "John@gmail.com"
}
},
{
id: 2,
userDetails: {
userName: "Carol",
userMailId: "Carol@gmail.com"
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e95ff5ced011c280a0905c7"),
ObjectId("5e95ff71ed011c280a0905c8")
]
}
Example: Update Nested Field
Update Carol's email address without overwriting the userDetails object ?
db.demo601.update(
{ _id: ObjectId("5e95ff71ed011c280a0905c8") },
{ $set: { "userDetails.userMailId": "Carol@yahoo.com" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo601.find();
{
"_id": ObjectId("5e95ff5ced011c280a0905c7"),
"id": 1,
"userDetails": {
"userName": "John",
"userMailId": "John@gmail.com"
}
}
{
"_id": ObjectId("5e95ff71ed011c280a0905c8"),
"id": 2,
"userDetails": {
"userName": "Carol",
"userMailId": "Carol@yahoo.com"
}
}
Key Points
- Use
$setto update specific fields without affecting other document properties - Use dot notation (
"userDetails.userMailId") to update nested object fields - Without
$set, the entire document would be replaced
Conclusion
The $set operator ensures safe updates by modifying only the specified fields while preserving the rest of the document structure. Use dot notation for nested field updates to prevent overwriting parent objects.
Advertisements
