0
0
MongoDBquery~3 mins

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

Choose your learning style9 modes available
The Big Idea

What if you could add many items to your list with just one simple command?

The Scenario

Imagine you have a list of favorite movies stored in a database for each user. Now, you want to add multiple new movies to a user's list one by one manually.

The Problem

Adding each movie separately means many database calls, which is slow and can cause mistakes like missing some movies or adding duplicates. It's like writing down each movie title on a paper one by one instead of all at once.

The Solution

The $each modifier with $push lets you add many items to an array in a single, simple command. This saves time, reduces errors, and keeps your data neat and consistent.

Before vs After
Before
db.users.updateOne({_id: 1}, {$push: {movies: 'Inception'}})
db.users.updateOne({_id: 1}, {$push: {movies: 'Interstellar'}})
After
db.users.updateOne({_id: 1}, {$push: {movies: {$each: ['Inception', 'Interstellar']}}})
What It Enables

You can efficiently add many items to a list in one go, making your database updates faster and your code cleaner.

Real Life Example

A streaming app adds multiple new recommended shows to a user's watchlist at once, improving performance and user experience.

Key Takeaways

Manually adding items one by one is slow and error-prone.

$each with $push adds multiple items in a single update.

This makes database operations faster and simpler.