0
0
MongoDBquery~3 mins

Why $slice modifier with $push in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add items to a list and keep it perfectly sized with just one command?

The Scenario

Imagine you have a list of recent messages in a chat app stored as an array. You want to add new messages but keep only the latest 10 to save space.

The Problem

Manually checking the array length and removing old messages every time you add a new one is slow and error-prone. It requires extra code and can easily break if you forget to trim the list.

The Solution

The $slice modifier with $push lets you add new items and automatically keep the array size limited in one simple step. This keeps your data clean and your code simple.

Before vs After
Before
messages.push(newMessage);
if (messages.length > 10) {
  messages.shift();
}
After
db.collection.updateOne(
  { _id: chatId },
  { $push: { messages: { $each: [newMessage], $slice: -10 } } }
)
What It Enables

You can efficiently maintain fixed-size lists in your database without extra code or errors.

Real Life Example

In a social media app, keep only the latest 10 notifications per user by pushing new ones and slicing the array automatically.

Key Takeaways

Manually managing array size is complicated and error-prone.

$slice with $push trims arrays automatically when adding items.

This keeps your data tidy and your code simple.