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 only a specific value in a MongoDB document
To update only a specific value in a MongoDB document, use the $set operator with update() or updateOne(). This operator modifies only the specified fields without affecting other document data.
Syntax
db.collection.updateOne(
{ "field": "matchValue" },
{ $set: { "fieldToUpdate": "newValue" } }
);
Create Sample Data
db.demo201.insertMany([
{ "ClientName": "Chris Brown", "ClientAge": 26 },
{ "ClientName": "David Miller", "ClientAge": 35 },
{ "ClientName": "Carol Taylor", "ClientAge": 28 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3c39ca03d395bdc21346e5"),
ObjectId("5e3c39d403d395bdc21346e6"),
ObjectId("5e3c39e603d395bdc21346e7")
]
}
Display all documents from the collection ?
db.demo201.find();
{ "_id": ObjectId("5e3c39ca03d395bdc21346e5"), "ClientName": "Chris Brown", "ClientAge": 26 }
{ "_id": ObjectId("5e3c39d403d395bdc21346e6"), "ClientName": "David Miller", "ClientAge": 35 }
{ "_id": ObjectId("5e3c39e603d395bdc21346e7"), "ClientName": "Carol Taylor", "ClientAge": 28 }
Example: Update Specific Field
Update the ClientName for the document with ClientAge 35 ?
db.demo201.updateOne(
{ "ClientAge": 35 },
{ $set: { "ClientName": "John Doe" } }
);
{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1
}
Verify Result
db.demo201.find();
{ "_id": ObjectId("5e3c39ca03d395bdc21346e5"), "ClientName": "Chris Brown", "ClientAge": 26 }
{ "_id": ObjectId("5e3c39d403d395bdc21346e6"), "ClientName": "John Doe", "ClientAge": 35 }
{ "_id": ObjectId("5e3c39e603d395bdc21346e7"), "ClientName": "Carol Taylor", "ClientAge": 28 }
Key Points
-
$setupdates only the specified fields, leaving other fields unchanged -
updateOne()updates the first matching document - Use
updateMany()to update all matching documents
Conclusion
The $set operator allows precise field updates without modifying the entire document. Use updateOne() for single document updates and updateMany() for multiple documents.
Advertisements
