0
0
MongoDBquery~5 mins

$each modifier with $push in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $each modifier with $push
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding each item from the $each array to the target array.
  • How many times: Once for each item in the $each array.
How Execution Grows With Input

As the number of items in the $each array grows, the number of operations grows roughly the same way.

Input Size (n)Approx. Operations
1010 additions to the array
100100 additions to the array
10001000 additions to the array

Pattern observation: The work grows directly with the number of items added.

Final Time Complexity

Time Complexity: O(n)

This means the time to add items grows in a straight line with the number of items you add.

Common Mistake

[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.

Interview Connect

Understanding how batch updates like $push with $each scale helps you reason about database performance and write efficient queries in real projects.

Self-Check

"What if we used $addToSet with $each instead of $push? How would the time complexity change?"