MongoDB Drop Database

MongoDB provides the ability to drop databases to clean up databases that are no longer needed. The drop operation is irreversible, so please use with caution.

Drop Current Database

Basic Syntax

db.dropDatabase()

Example

// Switch to the database to be dropped
use mydb

// Drop current database
db.dropDatabase()

// Output:
// { "dropped" : "mydb", "ok" : 1 }

Pre-Deletion Confirmation

View Current Database

// Confirm current database
db
// Output: mydb

// View database statistics
db.stats()

View Collection List

show collections

// Or
db.getCollectionNames()

Complete Confirmation Flow

use mydb

// 1. Confirm database name
print("Current database:", db.getName())

// 2. View collection list
print("Contains collections:", db.getCollectionNames())

// 3. View document count
print("Total documents:", db.stats().objects)

// 4. View data size
print("Data size:", db.stats().dataSize, "bytes")

Safe Deletion Process

Step 1: Backup Data

# Backup using mongodump
mongodump --db mydb --out /backup/$(date +%Y%m%d)

# Or backup with authentication
mongodump --db mydb --username admin --password xxx --authenticationDatabase admin --out /backup/

Step 2: Verify Backup

# View backup directory
ls -la /backup/

# Verify backup files
mongorestore --dryRun /backup/mydb/

Step 3: Execute Deletion

use mydb

// Confirm again
if (db.getName() === "mydb") {
    db.dropDatabase()
    print("Database dropped")
} else {
    print("Database name mismatch, canceling deletion")
}

Drop Specific Database (Non-Current)

MongoDB doesn't have a direct command to drop non-current databases; you need to switch first:

// Method: Switch to target database then drop
use targetdb
db.dropDatabase()

Drop Multiple Databases

Batch Deletion Example

// List of databases to delete
var dbsToDelete = ["testdb1", "testdb2", "tempdb"]

dbsToDelete.forEach(function(dbName) {
    var currentDb = db.getSiblingDB(dbName)
    
    // Check if database exists
    var dbList = db.adminCommand({ listDatabases: 1 })
    var exists = dbList.databases.some(function(d) {
        return d.name === dbName
    })
    
    if (exists) {
        print("Dropping database:", dbName)
        currentDb.dropDatabase()
        print("Dropped:", dbName)
    } else {
        print("Database does not exist:", dbName)
    }
})

Drop Protection Mechanisms

Prevent Accidental Production Database Deletion

1. Use Admin Permission Control

// Create user with specific permissions only
use admin

db.createUser({
  user: "dbadmin",
  pwd: "password",
  roles: [
    { role: "dbAdmin", db: "testdb" },      // Can only manage test database
    { role: "read", db: "productiondb" }     // Production database read-only
  ]
})

2. Script Protection

// safe-drop.js
var targetDb = "mydb"
var confirmName = "mydb"  // Manual confirmation required

if (targetDb === confirmName) {
    db.getSiblingDB(targetDb).dropDatabase()
    print("Database dropped:", targetDb)
} else {
    print("Confirmation name mismatch, canceling deletion")
}

Pre-Deletion Checklist

function safeDropDatabase(dbName) {
    var targetDb = db.getSiblingDB(dbName)
    
    // Check 1: Database exists
    var dbList = db.adminCommand({ listDatabases: 1 })
    var exists = dbList.databases.some(function(d) {
        return d.name === dbName
    })
    
    if (!exists) {
        print("Error: Database does not exist")
        return false
    }
    
    // Check 2: Not a system database
    var systemDbs = ["admin", "local", "config"]
    if (systemDbs.indexOf(dbName) !== -1) {
        print("Error: Cannot drop system database")
        return false
    }
    
    // Check 3: Get statistics
    var stats = targetDb.stats()
    print("Database:", dbName)
    print("Collections:", stats.collections)
    print("Documents:", stats.objects)
    print("Data size:", stats.dataSize, "bytes")
    
    // Execute drop
    var result = targetDb.dropDatabase()
    return result.ok === 1
}

// Usage
safeDropDatabase("mydb")

Restore Deleted Database

Restore from Backup

# Restore using mongorestore
mongorestore --db mydb /backup/20240120/mydb/

# Restore to different database name
mongorestore --db mydb_new /backup/20240120/mydb/

Restore from Replica Set

If replica set is configured, can restore from secondary:

# Stop secondary
# Copy data files
# Restart

Common Questions

Q: Space not released after dropping database?

A: MongoDB doesn't immediately release disk space; use compact command:

// Compact collection to release space
db.collection.compact()

// Or use repairDatabase (requires downtime)
db.repairDatabase()

Q: How to delete all user data but keep structure?

A: Drop all collections instead of dropping database:

db.getCollectionNames().forEach(function(col) {
    if (!col.startsWith("system.")) {
        db[col].drop()
    }
})

Q: How long does the drop operation take?

A: Depends on data volume:

  • Small database (<1GB): Almost instantaneous
  • Large database (>100GB): May take several minutes

Command Line Deletion

Non-Interactive Deletion

# Execute drop command directly
mongosh --eval "db.getSiblingDB('mydb').dropDatabase()"

# With authentication
mongosh -u admin -p --authenticationDatabase admin --eval "db.getSiblingDB('mydb').dropDatabase()"

Script Deletion

#!/bin/bash
# drop-db.sh

DB_NAME=$1
BACKUP_DIR="/backup/$(date +%Y%m%d)"

if [ -z "$DB_NAME" ]; then
    echo "Usage: $0 <database_name>"
    exit 1
fi

# Backup
echo "Backing up database..."
mongodump --db $DB_NAME --out $BACKUP_DIR

# Drop
echo "Dropping database..."
mongosh --eval "db.getSiblingDB('$DB_NAME').dropDatabase()"

echo "Complete"

Summary

Important notes for dropping databases:

  • Irreversible operation: Always backup before dropping
  • Confirm current database: Use db command to confirm
  • Protect system databases: Don't drop admin, local, config
  • Monitor disk space: May need to compact to release space after deletion

In the next chapter, we will learn about MongoDB Create Collection.