Push and slice multiple times in MongoDB?

To push and slice multiple times in MongoDB, use the $push operator with $each and $slice modifiers. The $slice operator limits the array size, keeping only the specified number of elements after each push operation.

Syntax

db.collection.update(
    { "field": "value" },
    {
        "$push": {
            "arrayField": {
                "$each": ["newElement"],
                "$slice": -N
            }
        }
    }
);

Create Sample Data

db.demo656.insertOne({Name: "John"});
{
    "acknowledged": true,
    "insertedId": ObjectId("5ea060264deddd72997713cf")
}
db.demo656.find();
{ "_id": ObjectId("5ea060264deddd72997713cf"), "Name": "John" }

Example 1: First Push and Slice Operation

Push "John" to the ListOfName array and limit it to the last 9 elements ?

db.demo656.update(
    {Name: "John"}, 
    {
        "$push": {
            "ListOfName": {
                "$each": ["John"], 
                "$slice": -9
            }
        }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
db.demo656.find();
{ "_id": ObjectId("5ea060264deddd72997713cf"), "Name": "John", "ListOfName": ["John"] }

Example 2: Second Push and Slice Operation

Push "David" to the same array while maintaining the slice limit ?

db.demo656.update(
    {Name: "John"}, 
    {
        "$push": {
            "ListOfName": {
                "$each": ["David"], 
                "$slice": -9
            }
        }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
db.demo656.find();
{ "_id": ObjectId("5ea060264deddd72997713cf"), "Name": "John", "ListOfName": ["John", "David"] }

Key Points

  • $slice: -N keeps the last N elements in the array after each push operation.
  • $each allows pushing multiple elements in a single operation.
  • The slice operation occurs after the push, maintaining the array size limit.

Conclusion

Using $push with $slice enables controlled array growth by automatically limiting array size after each addition. This is useful for maintaining fixed-size arrays like recent activity logs or latest entries.

Updated on: 2026-03-15T03:25:44+05:30

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements