MongoDB query to update array with another field?

To update an array with another field in MongoDB, use the $push operator along with $each to add multiple values at once. The $slice modifier can limit the array size.

Syntax

db.collection.update(
    {filter},
    {
        $push: {
            arrayField: {
                $each: ["value1", "value2"],
                $slice: maxArraySize
            }
        }
    }
);

Sample Data

db.demo283.insertOne({
    "Name": "Chris",
    "Status": ["Active", "Inactive"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e4ab97ddd099650a5401a75")
}

Display the document to verify initial data ?

db.demo283.find();
{
    "_id": ObjectId("5e4ab97ddd099650a5401a75"),
    "Name": "Chris",
    "Status": ["Active", "Inactive"]
}

Example: Update Array with Multiple Values

Add "Regular" and "NotRegular" to the Status array and limit array size to 4 elements ?

db.demo283.update(
    {},
    {
        $push: {
            Status: {
                $each: ["Regular", "NotRegular"],
                $slice: -4
            }
        }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify the updated document ?

db.demo283.find();
{
    "_id": ObjectId("5e4ab97ddd099650a5401a75"),
    "Name": "Chris",
    "Status": ["Active", "Inactive", "Regular", "NotRegular"]
}

Key Points

  • $each allows adding multiple values to an array in a single operation.
  • $slice: -4 keeps only the last 4 elements, useful for maintaining array size limits.
  • Use empty filter {} to update all documents in the collection.

Conclusion

The $push operator with $each efficiently adds multiple values to arrays. Combine with $slice to control array size and prevent unlimited growth in your MongoDB collections.

Updated on: 2026-03-15T02:17:33+05:30

408 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements