0
0
MongoDBquery~5 mins

$push operator for adding to arrays in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $push operator for adding to arrays
O(1)
Understanding Time Complexity

When we add items to arrays in MongoDB using the $push operator, it is important to understand how the time it takes grows as the array gets bigger.

We want to know how the work changes when the array has more elements.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    db.collection.updateOne(
      { _id: 1 },
      { $push: { items: "newItem" } }
    )
    

This code adds a new element to the end of the items array inside a document with _id 1.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding one element to the end of an array.
  • How many times: This happens once per update call.
How Execution Grows With Input

Adding one item to the end of an array usually takes the same amount of time no matter how big the array is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time to add one element stays about the same even if the array grows larger.

Final Time Complexity

Time Complexity: O(1)

This means adding an element with $push takes a constant amount of time regardless of the array size.

Common Mistake

[X] Wrong: "Adding an item with $push takes longer as the array gets bigger because it has to move all elements."

[OK] Correct: MongoDB stores arrays so it can add items at the end quickly without moving existing elements, so the time stays constant.

Interview Connect

Understanding how simple operations like $push scale helps you explain database performance clearly and confidently in interviews.

Self-Check

"What if we used $push with $each to add multiple items at once? How would the time complexity change?"