updateMany method in MongoDB - Time & Space Complexity
When using the updateMany method in MongoDB, it's important to understand how the time it takes grows as the number of documents increases.
We want to know how the work done changes when more documents match the update criteria.
Analyze the time complexity of the following code snippet.
db.collection.updateMany(
{ status: "pending" },
{ $set: { status: "complete" } }
)
This code updates all documents with status equal to "pending" by setting their status to "complete".
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning documents that match the filter and updating each one.
- How many times: Once for each document that matches the filter condition.
As the number of matching documents grows, the update operation must touch each one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document updates |
| 100 | About 100 document updates |
| 1000 | About 1000 document updates |
Pattern observation: The work grows directly with the number of documents to update.
Time Complexity: O(n)
This means the time to complete the update grows linearly with the number of documents that match the filter.
[X] Wrong: "The updateMany method updates all documents instantly, no matter how many match."
[OK] Correct: Each matching document must be individually updated, so more matches mean more work and more time.
Understanding how updateMany scales helps you explain how database operations behave with growing data, a useful skill for real projects and interviews.
"What if we added an index on the status field? How would the time complexity of updateMany change?"