0
0
MongoDBquery~5 mins

Drop collection vs deleteMany in MongoDB

Choose your learning style9 modes available
Introduction

We use drop to remove a whole collection and deleteMany to remove some or all documents inside a collection without deleting the collection itself.

When you want to completely remove a collection and all its data.
When you want to clear all or some documents but keep the collection structure.
When you want to reset a collection for fresh data without recreating it.
When you want to delete documents matching a specific condition.
When you want to free up space by removing unwanted documents but keep indexes.
Syntax
MongoDB
db.collection.drop()
db.collection.deleteMany(filter)

drop() removes the entire collection including indexes.

deleteMany(filter) removes documents matching the filter but keeps the collection and indexes.

Examples
Deletes the entire users collection and all its data.
MongoDB
db.users.drop()
Deletes all users younger than 18 but keeps the users collection.
MongoDB
db.users.deleteMany({ age: { $lt: 18 } })
Deletes all documents in the orders collection but keeps the collection itself.
MongoDB
db.orders.deleteMany({})
Sample Program

This example first inserts three products. Then it deletes products cheaper than 2 (Pen and Eraser). Next, it shows remaining products (Notebook). Finally, it drops the whole products collection and checks if it still exists.

MongoDB
use shopDB

// Create collection and insert sample data
db.products.insertMany([
  { name: "Pen", price: 1.5 },
  { name: "Notebook", price: 3 },
  { name: "Eraser", price: 0.5 }
])

// Delete all products cheaper than 2
const deleteResult = db.products.deleteMany({ price: { $lt: 2 } })

// Check remaining documents
const remaining = db.products.find().toArray()

// Drop the entire collection
const dropResult = db.products.drop()

// Check if collection exists
const collections = db.getCollectionNames()
OutputSuccess
Important Notes

After drop(), the collection no longer exists and must be recreated to add data again.

deleteMany({}) deletes all documents but keeps the collection and indexes intact.

Use drop() carefully because it removes everything including indexes.

Summary

drop() removes the entire collection and all data.

deleteMany(filter) removes documents matching the filter but keeps the collection.

Choose drop() to remove collection completely, deleteMany to clear data selectively.