Array update with $[] all positional in MongoDB - Time & Space Complexity
When updating all elements in an array inside MongoDB documents, it's important to understand how the time taken grows as the array size increases.
We want to know how the update operation scales when using the $[] all positional operator.
Analyze the time complexity of the following MongoDB update operation.
db.collection.updateMany(
{},
{ $set: { "items.$[]": "updated" } }
)
This code updates every element in the items array of all documents by setting each element to the string "updated".
Look for repeated work inside the update.
- Primary operation: Updating each element in the
itemsarray. - How many times: Once for every element in the array, for every matched document.
The time to update grows as the number of elements in the array grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Updates 10 elements per document |
| 100 | Updates 100 elements per document |
| 1000 | Updates 1000 elements per document |
Pattern observation: The work increases directly with the number of array elements; doubling elements roughly doubles the update work.
Time Complexity: O(n)
This means the update time grows linearly with the number of elements in the array being updated.
[X] Wrong: "Using $[] updates all array elements instantly, so time does not depend on array size."
[OK] Correct: Each element must be individually updated, so the time grows with the number of elements.
Understanding how array updates scale helps you explain performance trade-offs clearly, a skill valued in real-world database work and interviews.
What if we changed $[] to update only the first matching element with $? How would the time complexity change?