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 specific fields in MongoDB?
To update only specific fields in MongoDB, use the $set operator. This operator modifies the value of a field without affecting other fields in the document.
Syntax
db.collection.update(
{ "field": "matchValue" },
{ $set: { "fieldToUpdate": "newValue" } }
);
Sample Data
db.updateOnlySpecificFieldDemo.insertMany([
{ "EmployeeName": "John", "EmployeeCountryName": "UK" },
{ "EmployeeName": "Larry", "EmployeeCountryName": "US" },
{ "EmployeeName": "David", "EmployeeCountryName": "AUS" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9ea849d628fa4220163b72"),
ObjectId("5c9ea853d628fa4220163b73"),
ObjectId("5c9ea85bd628fa4220163b74")
]
}
Display All Documents
db.updateOnlySpecificFieldDemo.find().pretty();
{
"_id": ObjectId("5c9ea849d628fa4220163b72"),
"EmployeeName": "John",
"EmployeeCountryName": "UK"
}
{
"_id": ObjectId("5c9ea853d628fa4220163b73"),
"EmployeeName": "Larry",
"EmployeeCountryName": "US"
}
{
"_id": ObjectId("5c9ea85bd628fa4220163b74"),
"EmployeeName": "David",
"EmployeeCountryName": "AUS"
}
Example: Update Specific Field
Update only the "EmployeeName" field for the document with specific _id ?
db.updateOnlySpecificFieldDemo.update(
{ _id: ObjectId("5c9ea849d628fa4220163b72") },
{ $set: { "EmployeeName": "Robert" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.updateOnlySpecificFieldDemo.find().pretty();
{
"_id": ObjectId("5c9ea849d628fa4220163b72"),
"EmployeeName": "Robert",
"EmployeeCountryName": "UK"
}
{
"_id": ObjectId("5c9ea853d628fa4220163b73"),
"EmployeeName": "Larry",
"EmployeeCountryName": "US"
}
{
"_id": ObjectId("5c9ea85bd628fa4220163b74"),
"EmployeeName": "David",
"EmployeeCountryName": "AUS"
}
Conclusion
The $set operator updates only the specified field while preserving all other existing fields. This makes it ideal for partial document updates without overwriting the entire document.
Advertisements
