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

  • $set updates the nested field Details.Name from "David" to "John Doe"
  • $push creates a new array field StudentAge and 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.

Updated on: 2026-03-15T02:14:38+05:30

924 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements