Bird
Raised Fist0
MongoDBquery~10 mins

$push operator for adding to arrays in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - $push operator for adding to arrays
Start with document
Locate array field
$push operator adds element
Array grows by one element
Save updated document
The $push operator finds the array field in a document and adds a new element to the end of that array, then saves the updated document.
Execution Sample
MongoDB
db.users.updateOne(
  { name: "Alice" },
  { $push: { hobbies: "reading" } }
)
This command adds the string "reading" to the hobbies array of the user named Alice.
Execution Table
StepActionDocument BeforeArray Field BeforeElement AddedArray Field AfterDocument After
1Find document with name 'Alice'{ name: 'Alice', hobbies: ['swimming', 'cycling'] }['swimming', 'cycling']['swimming', 'cycling']{ name: 'Alice', hobbies: ['swimming', 'cycling'] }
2Apply $push to hobbies array{ name: 'Alice', hobbies: ['swimming', 'cycling'] }['swimming', 'cycling']"reading"['swimming', 'cycling', 'reading']{ name: 'Alice', hobbies: ['swimming', 'cycling', 'reading'] }
3Save updated document{ name: 'Alice', hobbies: ['swimming', 'cycling', 'reading'] }['swimming', 'cycling', 'reading']['swimming', 'cycling', 'reading']{ name: 'Alice', hobbies: ['swimming', 'cycling', 'reading'] }
4ExitUpdate complete
💡 Update completes after adding element to array and saving document
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
Document{ name: 'Alice', hobbies: ['swimming', 'cycling'] }{ name: 'Alice', hobbies: ['swimming', 'cycling'] }{ name: 'Alice', hobbies: ['swimming', 'cycling', 'reading'] }{ name: 'Alice', hobbies: ['swimming', 'cycling', 'reading'] }{ name: 'Alice', hobbies: ['swimming', 'cycling', 'reading'] }
hobbies array['swimming', 'cycling']['swimming', 'cycling']['swimming', 'cycling', 'reading']['swimming', 'cycling', 'reading']['swimming', 'cycling', 'reading']
Key Moments - 3 Insights
What happens if the array field does not exist in the document?
If the array field does not exist, $push creates the array field and adds the element as the first item. This is not shown in the table but is important to know.
Does $push add the element to the beginning or end of the array?
$push always adds the element to the end of the array, as shown in step 2 where "reading" is added after existing elements.
What if the field is not an array but a different type?
If the field is not an array, $push will cause an error because it expects an array to add elements to.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the hobbies array after step 2?
A['swimming', 'cycling']
B['swimming', 'cycling', 'reading']
C['reading', 'swimming', 'cycling']
D[]
💡 Hint
Check the 'Array Field After' column in row with Step 2
At which step is the new element actually added to the array?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Element Added' and 'Array Field After' columns in the execution table
If the hobbies field did not exist before, what would $push do?
ADo nothing
BThrow an error
CCreate hobbies as an array with the new element
DReplace the document
💡 Hint
Refer to key moments about missing array field behavior
Concept Snapshot
$push operator adds an element to the end of an array field in a MongoDB document.
Syntax: { $push: { arrayField: newElement } }
If the array field doesn't exist, it creates it.
If the field is not an array, it causes an error.
Used in update commands like updateOne or updateMany.
Full Transcript
The $push operator in MongoDB updates a document by adding a new element to the end of an existing array field. The process starts by finding the document, then locating the array field. The new element is added to the end of this array, and the updated document is saved. If the array field does not exist, $push creates it with the new element as the first item. If the field is not an array, an error occurs. This operator is useful for growing arrays inside documents without replacing the whole array.

Practice

(1/5)
1. What does the $push operator do in MongoDB?
easy
A. Adds a new element to the end of an array field in a document
B. Removes an element from an array field in a document
C. Replaces the entire array field with a new array
D. Creates a new collection in the database

Solution

  1. Step 1: Understand the purpose of $push

    The $push operator is used to add elements to an existing array field inside a MongoDB document.
  2. Step 2: Compare with other options

    Options A, C, and D describe different operations: removing elements, replacing arrays, or creating collections, which are not what $push does.
  3. Final Answer:

    Adds a new element to the end of an array field in a document -> Option A
  4. Quick Check:

    $push adds elements [OK]
Hint: Remember: $push always adds to array end [OK]
Common Mistakes:
  • Confusing $push with $pull (which removes items)
  • Thinking $push replaces the whole array
  • Mixing $push with collection creation commands
2. Which of the following is the correct syntax to add the value 5 to the array field numbers in a document where _id is 1?
easy
A. db.collection.updateOne({_id: 1}, {$push: {numbers: 5}})
B. db.collection.updateOne({_id: 1}, {$push: numbers: 5})
C. db.collection.updateOne({_id: 1}, {$push: {numbers => 5}})
D. db.collection.updateOne({_id: 1}, {$push: {numbers: [5]}})

Solution

  1. Step 1: Identify correct $push syntax

    The correct syntax uses an object with the field name as key and the value to add as value: {$push: {field: value}}.
  2. Step 2: Analyze each option

    db.collection.updateOne({_id: 1}, {$push: {numbers: 5}}) matches the correct syntax. db.collection.updateOne({_id: 1}, {$push: numbers: 5}) misses curly braces around the field-value pair. db.collection.updateOne({_id: 1}, {$push: {numbers => 5}}) uses an invalid arrow syntax. db.collection.updateOne({_id: 1}, {$push: {numbers: [5]}}) pushes the array [5] as a single element instead of adding the scalar value 5.
  3. Final Answer:

    db.collection.updateOne({_id: 1}, {$push: {numbers: 5}}) -> Option A
  4. Quick Check:

    Correct $push syntax uses {$push: {field: value}} [OK]
Hint: Use {$push: {field: value}} with braces [OK]
Common Mistakes:
  • Omitting braces around field-value pair
  • Using wrong symbols like => instead of :
  • Pushing an array when a single value is intended
3. Given the document { _id: 1, tags: ["red", "blue"] }, what will be the tags array after running db.collection.updateOne({_id: 1}, {$push: {tags: "green"}})?
medium
A. ["red", "blue"]
B. ["red", "green", "blue"]
C. ["green", "red", "blue"]
D. ["red", "blue", "green"]

Solution

  1. Step 1: Understand $push effect on array

    The $push operator adds the new element to the end of the existing array.
  2. Step 2: Apply $push to the given array

    Starting with ["red", "blue"], pushing "green" adds it at the end, resulting in ["red", "blue", "green"].
  3. Final Answer:

    ["red", "blue", "green"] -> Option D
  4. Quick Check:

    New item added at array end [OK]
Hint: Remember $push adds at the end of array [OK]
Common Mistakes:
  • Assuming $push adds at the start
  • Replacing the whole array instead of adding
  • Confusing order of elements after push
4. You want to add multiple values ["yellow", "purple"] to the colors array in a document with _id: 2. Which update command will NOT work correctly?
medium
A. db.collection.updateOne({_id: 2}, {$push: {colors: { $each: ["yellow", "purple"] }}})
B. db.collection.updateOne({_id: 2}, {$push: {colors: ["yellow", "purple"]}})
C. db.collection.updateOne({_id: 2}, {$push: {colors: {$each: ["yellow", "purple"]}}})
D. db.collection.updateOne({_id: 2}, {$push: {colors: { $each: ["yellow", "purple" ] }}})

Solution

  1. Step 1: Understand how to push multiple items

    To add multiple items to an array, $push must be combined with $each inside the update document.
  2. Step 2: Analyze each option

    Options B, C, and D correctly use $each to add multiple values. db.collection.updateOne({_id: 2}, {$push: {colors: ["yellow", "purple"]}}) tries to push an array directly, which will add the entire array as a single element, not multiple elements.
  3. Final Answer:

    db.collection.updateOne({_id: 2}, {$push: {colors: ["yellow", "purple"]}}) -> Option B
  4. Quick Check:

    Use $each to push multiple items [OK]
Hint: Use $each inside $push for multiple items [OK]
Common Mistakes:
  • Pushing an array directly instead of using $each
  • Forgetting curly braces around $each
  • Using wrong operators like $addToSet instead of $push
5. You have a document { _id: 3, tasks: ["task1"] }. You want to add "task2" and "task3" only if they are not already in the array. Which update command correctly achieves this?
hard
A. db.collection.updateOne({_id: 3}, {$push: {tasks: { $each: ["task2", "task3"] }}})
B. db.collection.updateOne({_id: 3}, {$push: {tasks: { $addToSet: ["task2", "task3"] }}})
C. db.collection.updateOne({_id: 3}, {$addToSet: {tasks: { $each: ["task2", "task3"] }}})
D. db.collection.updateOne({_id: 3}, {$push: {tasks: ["task2", "task3"]}})

Solution

  1. Step 1: Understand difference between $push and $addToSet

    $push adds items regardless of duplicates. $addToSet adds items only if they don't exist already.
  2. Step 2: Analyze the commands

    db.collection.updateOne({_id: 3}, {$addToSet: {tasks: { $each: ["task2", "task3"] }}}) uses $addToSet with $each to add multiple unique items. Options A and D use $push which can add duplicates. db.collection.updateOne({_id: 3}, {$push: {tasks: { $addToSet: ["task2", "task3"] }}}) incorrectly nests $addToSet inside $push, which is invalid syntax.
  3. Final Answer:

    db.collection.updateOne({_id: 3}, {$addToSet: {tasks: { $each: ["task2", "task3"] }}}) -> Option C
  4. Quick Check:

    Use $addToSet with $each for unique additions [OK]
Hint: Use $addToSet with $each to avoid duplicates [OK]
Common Mistakes:
  • Using $push when duplicates should be avoided
  • Nesting $addToSet inside $push incorrectly
  • Forgetting $each when adding multiple items