Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Efficient way to remove all entries from MongoDB?
MongoDB provides two main methods to remove all entries from a collection: drop() and remove(). The key difference is that drop() deletes the entire collection including indexes, while remove() only deletes documents but preserves the collection structure and indexes.
Syntax
// Method 1: Drop entire collection (fastest)
db.collection.drop()
// Method 2: Remove all documents (preserves indexes)
db.collection.remove({})
// Method 3: Delete all documents (modern approach)
db.collection.deleteMany({})
Method 1: Using drop() (Recommended for Complete Removal)
Let us first create a collection with documents and indexes ?
db.dropWorkingDemo.createIndex({"FirstName":1});
db.dropWorkingDemo.insertOne({"FirstName":"John"});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdd8742bf3115999ed511e9")
}
Display all documents to verify ?
db.dropWorkingDemo.find();
{ "_id" : ObjectId("5cdd8742bf3115999ed511e9"), "FirstName" : "John" }
Now use drop() to remove everything ?
db.dropWorkingDemo.drop();
true
Check if indexes still exist ?
db.dropWorkingDemo.getIndexes();
[ ]
The collection and all indexes are completely removed.
Method 2: Using remove() (Preserves Structure)
Create a new collection with documents and indexes ?
db.removeDemo.createIndex({"FirstName":1});
db.removeDemo.insertOne({"FirstName":"John"});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdd8868bf3115999ed511ea")
}
Use remove() to delete all documents ?
db.removeDemo.remove({});
WriteResult({ "nRemoved" : 1 })
Check if indexes are preserved ?
db.removeDemo.getIndexes();
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.removeDemo"
},
{
"v" : 2,
"key" : {
"FirstName" : 1
},
"name" : "FirstName_1",
"ns" : "test.removeDemo"
}
]
Yes, both the default _id index and custom FirstName index are preserved.
Key Differences
| Method | Speed | Indexes | Collection | Use Case |
|---|---|---|---|---|
drop() |
Fastest | Removed | Removed | Complete cleanup |
remove({}) |
Slower | Preserved | Preserved | Keep structure |
Conclusion
Use drop() for complete collection removal when you don't need indexes. Use remove({}) when you want to preserve the collection structure and indexes for future use.
