Delete with filter conditions in MongoDB - Time & Space Complexity
When deleting documents in MongoDB using filter conditions, it's important to know how the time to delete grows as the data grows.
We want to understand how the number of documents affects the time it takes to find and delete matching items.
Analyze the time complexity of the following code snippet.
db.collection.deleteMany({ status: "inactive" })
This code deletes all documents where the status field equals "inactive".
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning documents to check if they match the filter condition.
- How many times: Once for each document in the collection or index entries if an index exists.
As the number of documents grows, the time to find matching documents grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of checks grows roughly in direct proportion to the number of documents.
Time Complexity: O(n)
This means the time to delete grows linearly with the number of documents to check.
[X] Wrong: "Deleting documents with a filter always takes the same time no matter how many documents exist."
[OK] Correct: The database must check documents to find matches, so more documents usually mean more work and longer time.
Understanding how delete operations scale helps you explain database performance clearly and shows you know how data size affects queries.
"What if we add an index on the status field? How would the time complexity change?"