$slice
The $slice update operator modifies an array by limiting its size. When used with the $push operator, it restricts the number of elements in an array, keeping only the specified number of most recent or oldest elements.
Parameters
-
field: The array field to modify. -
count: Maximum number of elements to keep. Positive values keep the first N elements, negative values keep the last N elements.
Example (MongoDB Shell)
The following example demonstrates how to use the $slice update operator with $push to maintain a fixed-size array of recent scores.
Create sample documents
db.students.insertOne({ _id: 1, name: "Alice", scores: [85, 90, 78] });
Query example
db.students.updateOne( { _id: 1 }, { $push: { scores: { $each: [92, 88], $slice: -3 } } } )
Output
{
"_id" : 1,
"name" : "Alice",
"scores" : [ 78, 92, 88 ]
}
In this example, the $slice: -3 modifier keeps only the last three elements after pushing new values to the array.
Code examples
To view a code example for using the $slice update operator, choose the tab for the language that you want to use: