MongoDB - Drop Database
MongoDB - Dropping a Database
Section titled “MongoDB - Dropping a Database”This chapter explains how to permanently delete an entire database in MongoDB, a command that should be used with extreme caution.
The dropDatabase() Method
Section titled “The dropDatabase() Method”The db.dropDatabase() command deletes the current database, removing all associated collections, documents, and indexes.
Syntax
Section titled “Syntax”To use this command, you must first switch to the context of the database you intend to drop.
// 1. Switch to the target databaseuse database_name_to_drop;
// 2. Execute the drop commanddb.dropDatabase();**CRITICAL WARNING:** This is a destructive and irreversible operation. Once a database is dropped, its data cannot be recovered without a prior backup. Always double-check the database name and ensure you have a recent backup before executing this command in any environment, especially production.Example
Section titled “Example”First, let’s view our existing databases.
> show databasesadmin ...MBconfig ...MBlocal ...MBNow, let’s create a temporary database temp_db and drop it.
> use temp_dbswitched to db temp_db
> db.my_collection.insertOne({ message: "This is a test" }){ acknowledged: true, insertedId: ObjectId(...) }
> show databasesadmin ...MBconfig ...MBlocal ...MBtemp_db ...MB
> db.dropDatabase(){ dropped: 'temp_db', ok: 1 }Finally, verify the database has been deleted.
> show databasesadmin ...MBconfig ...MBlocal ...MBSecurity and Best Practices
Section titled “Security and Best Practices”- Role-Based Access Control (RBAC): In a secure environment, the ability to drop a database is controlled by specific user roles. The
dropDatabaseaction is required on the database resource. This privilege should only be granted to administrative accounts. - Production Environments: Manually dropping a production database is extremely rare and dangerous. This operation is more typically found in automated scripts for setting up or tearing down development or testing environments.
- Backup First: Before any major destructive operation, perform a backup using tools like
mongodump. A command likemongodump --uri="<your-connection-string>" --archive="backup.gz" --gzipcan create a full backup of your database. - Confirmation: Some modern database clients or scripts build in a confirmation step, asking you to re-type the database name to prevent accidental deletion. This is a good practice to adopt in your own operational workflows.