MongoDB Drop Collection
MongoDB provides the ability to drop collections to clean up collections that are no longer needed. Dropping a collection removes all documents and indexes in the collection.
Drop Collection Methods
Basic Syntax
javascript
db.collection.drop()Example
javascript
// Drop users collection
db.users.drop()
// Returns true if drop successful
// Returns false if collection doesn't existCheck Before Drop
javascript
// Check if collection exists
if (db.getCollectionNames().indexOf("users") >= 0) {
db.users.drop()
print("Collection dropped")
} else {
print("Collection does not exist")
}Drop Collection Characteristics
What Gets Dropped
- All documents in the collection
- All indexes of the collection
- The collection itself
What Remains
- The database itself
- Other collections
- Database users and permissions
Performance Characteristics
- Drop operation is very fast (almost instantaneous)
- Doesn't block other operations
- Space is not immediately released (needs compact)
Drop Multiple Collections
Batch Drop
javascript
// List of collections to drop
var collectionsToDrop = ["temp_logs", "cache_data", "old_records"]
collectionsToDrop.forEach(function(colName) {
if (db.getCollectionNames().indexOf(colName) >= 0) {
db.getCollection(colName).drop()
print("Dropped collection:", colName)
} else {
print("Collection does not exist:", colName)
}
})Drop All Collections (Keep Database)
javascript
// Method 1: Iterate and drop
db.getCollectionNames().forEach(function(colName) {
if (!colName.startsWith("system.")) {
db.getCollection(colName).drop()
print("Dropped:", colName)
}
})
// Method 2: Using loop
var collections = db.getCollectionNames()
for (var i = 0; i < collections.length; i++) {
var colName = collections[i]
if (!colName.startsWith("system.")) {
db[colName].drop()
}
}Safe Drop Process
Step 1: Backup Data
bash
# Export collection
mongodump --db mydb --collection users --out /backup/
# Or use mongoexport
mongoexport --db mydb --collection users --out /backup/users.jsonStep 2: Confirm Information
javascript
// View collection statistics
db.users.stats()
// View document count
db.users.countDocuments()
// View indexes
db.users.getIndexes()Step 3: Execute Drop
javascript
// Safe drop function
function safeDropCollection(colName) {
// Confirm collection exists
if (db.getCollectionNames().indexOf(colName) === -1) {
print("Error: Collection does not exist -", colName)
return false
}
// Get statistics
var stats = db[colName].stats()
print("Collection:", colName)
print("Document count:", stats.count)
print("Data size:", stats.size, "bytes")
print("Index count:", stats.nindexes)
// Execute drop
var result = db[colName].drop()
if (result) {
print("Drop successful:", colName)
return true
} else {
print("Drop failed:", colName)
return false
}
}
// Usage
safeDropCollection("users")Drop vs Empty Comparison
drop() vs deleteMany()
| Feature | drop() | deleteMany() |
|---|---|---|
| What gets deleted | Collection + documents + indexes | Documents only |
| Speed | Very fast | Depends on document count |
| Indexes | Dropped | Preserved |
| Space release | Needs compact | Not released |
| Recoverability | Low | Can rollback (in transactions) |
Empty Collection (Keep Structure)
javascript
// Method 1: deleteMany
db.users.deleteMany({})
// Method 2: remove (deprecated)
db.users.remove({})Command Line Drop
Non-Interactive Drop
bash
# Execute directly
mongosh --eval "db.getSiblingDB('mydb').users.drop()"
# With authentication
mongosh -u admin -p --authenticationDatabase admin --eval "db.getSiblingDB('mydb').users.drop()"Script Drop
bash
#!/bin/bash
# drop-collection.sh
DB_NAME=$1
COLLECTION_NAME=$2
if [ -z "$DB_NAME" ] || [ -z "$COLLECTION_NAME" ]; then
echo "Usage: $0 <database_name> <collection_name>"
exit 1
fi
# Backup
echo "Backing up collection..."
mongodump --db $DB_NAME --collection $COLLECTION_NAME --out /backup/
# Drop
echo "Dropping collection..."
mongosh --eval "db.getSiblingDB('$DB_NAME').$COLLECTION_NAME.drop()"
echo "Complete"Common Questions
Q: Space not released after dropping?
A: Use compact command to release space:
javascript
// Compact database
db.runCommand({ compact: "users" })Q: How to recover accidentally dropped collection?
A: Restore from backup:
bash
mongorestore --db mydb --collection users /backup/mydb/users.bsonQ: How to drop system collections?
A: Not recommended, but can use:
javascript
db.system.indexes.drop() // Use with caution!Summary
Key points for dropping collections:
- Operation is irreversible, backup before dropping
- Drops collection, documents, and indexes simultaneously
- Space is not immediately released
- Faster and more thorough than deleteMany()
In the next chapter, we will learn about MongoDB Insert Document.