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 only one property in MongoDB?
To update only one property in MongoDB, use the $set operator to modify a specific field without affecting other properties of the document. For arrays, use $addToSet or $push operators.
Syntax
db.collection.updateOne(
{ "field": "value" },
{ $set: { "propertyToUpdate": "newValue" } }
);
Sample Data
db.demo336.insertMany([
{ "Name": "Chris", "Score": [45, 67, 78] },
{ "Name": "David", "Score": [89, 93, 47] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e522cb1f8647eb59e562097"),
ObjectId("5e522cb2f8647eb59e562098")
]
}
Example 1: Update Single Property with $set
Update David's name to "David Smith" ?
db.demo336.updateOne(
{ "Name": "David" },
{ $set: { "Name": "David Smith" } }
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
Example 2: Add Values to Array Property
Add individual scores to David's Score array using $addToSet ?
db.demo336.updateOne(
{ "Name": "David" },
{ $addToSet: { "Score": { $each: [56, 34, 71] } } }
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
Verify Results
Display all documents to see the updates ?
db.demo336.find();
{ "_id": ObjectId("5e522cb1f8647eb59e562097"), "Name": "Chris", "Score": [45, 67, 78] }
{ "_id": ObjectId("5e522cb2f8647eb59e562098"), "Name": "David Smith", "Score": [89, 93, 47, 56, 34, 71] }
Key Points
-
$setupdates specific properties without affecting other fields -
$addToSetwith$eachadds multiple unique values to arrays - Use
updateOne()for single document updates
Conclusion
Use $set to update individual properties and $addToSet with $each for array modifications. These operators ensure only the target property is modified while preserving other document fields.
Advertisements
