The $slice modifier with $push helps you add items to an array but keep the array size limited. It removes extra items to keep only the newest or oldest ones.
0
0
$slice modifier with $push in MongoDB
Introduction
When you want to keep only the last 5 messages in a chat history array.
When you add new scores to a list but want to keep only the top 10 recent scores.
When you store recent user activities but want to limit the list size to save space.
When you want to add new items to a log but keep only the latest entries.
Syntax
MongoDB
db.collection.updateOne(
{ <query> },
{ $push: { <arrayField>: { $each: [ <value1>, <value2>, ... ], $slice: <number> } } }
)$each lets you add one or more values at once.
$slice keeps the array size to the number you specify after adding new items.
Examples
Adds 90 to Alice's scores array and keeps only the last 3 scores.
MongoDB
db.users.updateOne(
{ name: "Alice" },
{ $push: { scores: { $each: [90], $slice: -3 } } }
)Adds "login" event and keeps only the first 5 events in the array.
MongoDB
db.logs.updateOne(
{ _id: 1 },
{ $push: { events: { $each: ["login"], $slice: 5 } } }
)Sample Program
This example starts with Bob's scores as [70, 80]. We add 85 and 90 but keep only the last 3 scores. The final scores array will be [80, 85, 90].
MongoDB
use testdb // Insert a sample document db.users.insertOne({ name: "Bob", scores: [70, 80] }) // Add new scores and keep only last 3 scores db.users.updateOne( { name: "Bob" }, { $push: { scores: { $each: [85, 90], $slice: -3 } } } ) // Find the updated document db.users.findOne({ name: "Bob" })
OutputSuccess
Important Notes
If $slice is positive, it keeps that many items from the start of the array.
If $slice is negative, it keeps that many items from the end of the array.
You must use $each when using $slice with $push.
Summary
$slice with $push limits array size after adding new items.
Use $each to add multiple items at once.
Negative $slice keeps items from the end; positive keeps from the start.