$each modifier with $push in MongoDB - Time & Space Complexity
When we add multiple items to an array in MongoDB using $push with $each, it is important to understand how the time taken grows as we add more items.
We want to know how the work changes when the number of items we add increases.
Analyze the time complexity of the following code snippet.
db.collection.updateOne(
{ _id: 1 },
{ $push: { scores: { $each: [85, 90, 95] } } }
)
This code adds multiple scores to the scores array of a document with _id 1 using $push and $each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each item from the
$eacharray to the target array. - How many times: Once for each item in the
$eacharray.
As the number of items in the $each array grows, the number of operations grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions to the array |
| 100 | 100 additions to the array |
| 1000 | 1000 additions to the array |
Pattern observation: The work grows directly with the number of items added.
Time Complexity: O(n)
This means the time to add items grows in a straight line with the number of items you add.
[X] Wrong: "Adding multiple items with $each is done in constant time, no matter how many items there are."
[OK] Correct: Each item must be added one by one, so more items mean more work and more time.
Understanding how batch updates like $push with $each scale helps you reason about database performance and write efficient queries in real projects.
"What if we used $addToSet with $each instead of $push? How would the time complexity change?"