Drop collection vs deleteMany in MongoDB - Performance Comparison
When working with MongoDB, removing data can be done in different ways. Understanding how the time it takes grows with the amount of data helps us choose the right method.
We want to know how the cost changes when we drop a whole collection versus deleting many documents inside it.
Analyze the time complexity of these two MongoDB commands.
// Drop entire collection
db.collection.drop()
// Delete many documents matching a filter
db.collection.deleteMany({})
The first removes the whole collection and its data. The second deletes all documents but keeps the collection structure.
Look at what repeats inside each operation.
- Drop collection: No repeated document-level operations; it removes metadata and data in one step.
- deleteMany: Scans and deletes each document one by one.
- Primary operation: For deleteMany, the repeated deletion of each document dominates time.
- How many times: deleteMany repeats once per document; drop runs once regardless of size.
Think about how time changes as the number of documents grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | drop: 1 operation, deleteMany: 10 operations |
| 100 | drop: 1 operation, deleteMany: 100 operations |
| 1000 | drop: 1 operation, deleteMany: 1000 operations |
Pattern observation: drop time stays the same no matter how many documents; deleteMany time grows directly with the number of documents.
Time Complexity: O(1) for drop, O(n) for deleteMany
Dropping a collection takes the same time no matter its size, but deleting many documents takes longer as more documents exist.
[X] Wrong: "Deleting all documents with deleteMany is just as fast as dropping the collection."
[OK] Correct: deleteMany must remove each document one by one, so it takes longer as data grows. Drop removes everything at once, so it stays fast.
Knowing how these operations scale helps you explain choices clearly and shows you understand how databases handle data behind the scenes.
"What if deleteMany used an index to find documents faster? How would that affect the time complexity?"