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 do I set and push in single update with MongoDB?
To use $set and $push in a single MongoDB update operation, combine both operators within the same update document. The $set operator modifies existing field values, while $push adds elements to arrays.
Syntax
db.collection.update(
{ query },
{
$set: { "field1": "newValue" },
$push: { "arrayField": "newElement" }
}
);
Sample Data
db.dem0143.insertMany([
{ "StudentId": 1, "Details": { "Name": "Chris" } },
{ "StudentId": 2, "Details": { "Name": "David" } }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e32eb9efdf09dd6d08539b7"),
ObjectId("5e32eba5fdf09dd6d08539b8")
]
}
View Current Data
db.dem0143.find();
{ "_id": ObjectId("5e32eb9efdf09dd6d08539b7"), "StudentId": 1, "Details": { "Name": "Chris" } }
{ "_id": ObjectId("5e32eba5fdf09dd6d08539b8"), "StudentId": 2, "Details": { "Name": "David" } }
Example: Combining $set and $push
Update student with ID 2 to change the name and add age to an array ?
db.dem0143.update(
{ _id: ObjectId("5e32eba5fdf09dd6d08539b8") },
{
$set: { "Details.Name": "John Doe" },
$push: { "StudentAge": 21 }
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.dem0143.find();
{ "_id": ObjectId("5e32eb9efdf09dd6d08539b7"), "StudentId": 1, "Details": { "Name": "Chris" } }
{ "_id": ObjectId("5e32eba5fdf09dd6d08539b8"), "StudentId": 2, "Details": { "Name": "John Doe" }, "StudentAge": [21] }
Key Points
-
$setupdates the nested fieldDetails.Namefrom "David" to "John Doe" -
$pushcreates a new array fieldStudentAgeand adds the value 21 - Both operations execute atomically in a single update command
Conclusion
Combine $set and $push operators in one update operation to modify existing fields and add array elements simultaneously. This approach ensures atomic updates and reduces the number of database operations required.
Advertisements
