MongoDB Drop Database

In this article, we will see how to drop database in MongoDB server. MongoDB Drop Database is simple process. We have two methods one from Linux shell and another from Mongo shell. It’s very important to take the backup of database before dropping database.

To drop MongoDB database, logged in user must have ‘root’ role.

MongoDB Drop Database Syntax:

use database_name db.dropDatabase()

This removes the current database, deleting the associated data files.

MongoDB Drop Database from Mongo Shell:

1. Check the list of the database available.

> show dbs admin 0.000GB config 0.000GB local 0.000GB record 0.000GB sales 0.000GB test 0.000GB

2. Drop database from Mongo Shell:

From the above list, we drop database ‘record’.

> use record switched to db record > db.dropDatabase() { "dropped" : "record", "ok" : 1 }

Lets verify whether database is dropped or not.

> show dbs admin 0.000GB config 0.000GB local 0.000GB sales 0.000GB test 0.000GB

3. Drop database from Linux Shell:
MongoDB Drop Database Syntax from Linux Shell:

mongo --eval "db.dropDatabase()"

Examples:

mongo sales --eval "db.dropDatabase()"

Output:

MongoDB shell version v4.2.1 connecting to: mongodb://127.0.0.1:27017/sales?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("a170e7d0-9836-46f1-89a0-74c76adae955") } MongoDB server version: 4.2.1 { "dropped" : "sales", "ok" : 1 }

Lets verify database dropped successfully or not:

> show dbs admin 0.000GB config 0.000GB local 0.000GB test 0.000GB