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.
Practice
(1/5)
1. What does the $each modifier do when used with $push in MongoDB?
easy
A. It sorts the array elements after pushing a new value.
B. It adds multiple values to an array in a single update operation.
C. It replaces the entire array with a new set of values.
D. It removes multiple values from an array.
Solution
Step 1: Understand $push usage
$push adds elements to an array field in a document.
Step 2: Role of $each modifier
$each allows adding multiple elements at once inside $push, making the update efficient.
Final Answer:
It adds multiple values to an array in a single update operation. -> Option B
Quick Check:
$each adds many items [OK]
Hint: Remember: $each adds many items inside $push [OK]
Common Mistakes:
Thinking $each removes items
Using $each outside $push
Confusing $each with sorting
2. Which of the following is the correct syntax to add multiple values ["a", "b", "c"] to the array field tags using $push with $each?
A. The $each value must be an array, not separate strings.
B. The $push operator cannot be used with $each.
C. The field name items is invalid.
D. The update syntax is correct and will work as expected.
Solution
Step 1: Analyze $each value type
$each requires an array of values, but here it is given as separate strings without array brackets.
Step 2: Identify syntax error
Passing multiple strings without array brackets causes a syntax error in MongoDB update.
Final Answer:
The $each value must be an array, not separate strings. -> Option A
Quick Check:
$each needs array brackets [OK]
Hint: Always wrap $each values in square brackets [OK]
Common Mistakes:
Passing multiple values without array brackets
Confusing $each with $addToSet
Assuming $push alone can add multiple items
5. You want to add multiple new tags ["urgent", "review", "backend"] to the tags array of a document, but only if they are not already present. Which update operation correctly uses $push with $each and ensures no duplicates?