deleteMany method in MongoDB - Time & Space Complexity
When using the deleteMany 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 deletion criteria.
Analyze the time complexity of the following code snippet.
// Delete all documents where status is 'inactive'
db.users.deleteMany({ status: 'inactive' })
This code deletes all user documents that have the status set to 'inactive'.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning documents to find matches and deleting them.
- How many times: Once for each document that matches the filter.
As the number of documents matching the filter grows, the work to delete them grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document deletions |
| 100 | About 100 document deletions |
| 1000 | About 1000 document deletions |
Pattern observation: The time grows roughly in direct proportion to the number of documents deleted.
Time Complexity: O(n)
This means the time to delete grows linearly with the number of documents that match the filter.
[X] Wrong: "Deleting many documents is always instant regardless of how many match."
[OK] Correct: The database must check and remove each matching document, so more matches mean more work and more time.
Understanding how delete operations scale helps you explain database performance clearly and shows you know what happens behind the scenes.
"What if we added an index on the 'status' field? How would the time complexity change?"