0
0
MongoDBquery~5 mins

Drop collection vs deleteMany in MongoDB - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Drop collection vs deleteMany
O(1) for drop, O(n) for deleteMany
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Think about how time changes as the number of documents grows.

Input Size (n)Approx. Operations
10drop: 1 operation, deleteMany: 10 operations
100drop: 1 operation, deleteMany: 100 operations
1000drop: 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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Knowing how these operations scale helps you explain choices clearly and shows you understand how databases handle data behind the scenes.

Self-Check

"What if deleteMany used an index to find documents faster? How would that affect the time complexity?"