$push operator for adding to arrays in MongoDB - Time & Space 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.
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 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.
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 |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time to add one element stays about the same even if the array grows larger.
Time Complexity: O(1)
This means adding an element with $push takes a constant amount of time regardless of the array size.
[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.
Understanding how simple operations like $push scale helps you explain database performance clearly and confidently in interviews.
"What if we used $push with $each to add multiple items at once? How would the time complexity change?"