To drop a database in MongoDB, you need to use dropDatabase() method. The syntax is as follows:
db.dropDatabase()
The above syntax will delete the present working database. If you haven’t selected any database then it will delete the default database.
Before deleting the database, first list all the databases with the help of show command. The query is as follows:
> show dbs;
The following is the output:
admin 0.000GB config 0.000GB local 0.000GB sample 0.000GB
Here, let us delete the database ‘sample’. To delete the database ‘sample’, you need to switch the database with the help of use command. The syntax is as follows:
use yourDatabaseName;
The query is as follows:
> use sample; switched to db sample
Now you can delete the database ‘sample’. To delete the database, you need to use the dropDatabase() method as we discussed above.
The query is as follows:
> db.dropDatabase();
The following is the output:
{ "dropped" : "sample", "ok" : 1 }
Now to check whether the database ‘sample’ is deleted or not, you need to use the show command. The query is as follows:
> show dbs;
The following is the output:
admin 0.000GB config 0.000GB local 0.000GB
Look at the above sample output, there is no ‘sample’ database i.e. we deleted the database successfully.