0
0
MongoDBquery~5 mins

$each modifier with $push in MongoDB

Choose your learning style9 modes available
Introduction

The $each modifier lets you add multiple items to an array in one step. It works with $push to make adding many values easy and fast.

You want to add several new tags to a blog post's tags array at once.
You need to add multiple new friends to a user's friends list in one update.
You want to add several new scores to a player's score history in a game.
You are updating a product's list of available colors with many new options.
Syntax
MongoDB
db.collection.updateOne(
  { <filter> },
  { $push: { <arrayField>: { $each: [ <value1>, <value2>, ... ] } } }
)

The $each modifier must be inside $push.

You can add many values to the array in one update.

Examples
Adds "reading" and "hiking" to Alice's hobbies array.
MongoDB
db.users.updateOne(
  { name: "Alice" },
  { $push: { hobbies: { $each: ["reading", "hiking"] } } }
)
Adds three colors to the product's colors array.
MongoDB
db.products.updateOne(
  { sku: "123" },
  { $push: { colors: { $each: ["red", "blue", "green"] } } }
)
Sample Program

This example starts with a player named Bob who has scores 10 and 20. Then it adds three new scores (30, 40, 50) to his scores array using $each with $push. Finally, it shows the updated document.

MongoDB
use testdb

// Insert a sample document
db.players.insertOne({ name: "Bob", scores: [10, 20] })

// Add multiple scores at once
db.players.updateOne(
  { name: "Bob" },
  { $push: { scores: { $each: [30, 40, 50] } } }
)

// Find and show the updated document
printjson(db.players.findOne({ name: "Bob" }))
OutputSuccess
Important Notes

If the array field does not exist, $push with $each will create it.

You can combine $each with other modifiers like $sort or $slice to control the array after pushing.

Summary

$each lets you add many items to an array at once.

It must be used inside $push.

This makes updates simpler and faster when adding multiple values.