0
0
MongodbHow-ToBeginner · 3 min read

How to Drop a Database in MongoDB Quickly and Safely

To drop a database in MongoDB, first switch to the database using use databaseName, then run db.dropDatabase(). This command deletes the entire database and all its data permanently.
📐

Syntax

The command to drop a database in MongoDB is simple. First, select the database you want to delete with use databaseName. Then, execute db.dropDatabase() to remove it completely.

  • use databaseName: Switches to the target database.
  • db.dropDatabase(): Deletes the current database and all its collections.
mongodb
use myDatabase

db.dropDatabase()
Output
{ "dropped": "myDatabase", "ok": 1 }
💻

Example

This example shows how to drop a database named testDB. First, switch to testDB using use testDB. Then, run db.dropDatabase() to delete it. The output confirms the database was dropped.

mongodb
use testDB

db.dropDatabase()
Output
{ "dropped": "testDB", "ok": 1 }
⚠️

Common Pitfalls

Common mistakes when dropping a database include:

  • Not switching to the correct database before running db.dropDatabase().
  • Expecting a confirmation prompt—MongoDB drops the database immediately.
  • Accidentally dropping the wrong database because of a typo.

Always double-check the current database with db.getName() before dropping.

mongodb
use wrongDB
// Wrong database selected

db.dropDatabase()  // This deletes the wrong database

// Correct way:
use correctDB

db.dropDatabase()
📊

Quick Reference

CommandDescription
use databaseNameSwitch to the database you want to drop
db.dropDatabase()Delete the current database and all its data
db.getName()Check the name of the current database

Key Takeaways

Always switch to the target database using use databaseName before dropping.
The db.dropDatabase() command deletes the entire database immediately without confirmation.
Verify the current database with db.getName() to avoid accidental deletion.
Dropped databases cannot be recovered, so double-check before running the command.