How MongoDB Drop Database with DropDatabase() Method


1. Objective

In the previous MongoDB Tutorial, we have discussed How MongoDB create database, when we insert the values in a document and save it. We have also created a database with a name “dataflair”. In this Tutorial, we are going to learn How MongoDB Drop Database. Moreover, we will discuss the easy steps to drop database in MongoDB including dropDatabase() method.

So, let’s start with MongoDB Drop Database.

MongoDB Drop Database

Learn How MongoDB Drop Database with DropDatabase() Method

2. MongoDB Drop Database

In MongoDB Drop Database, a command is used to drop the database from it. For this purpose, we can use a dropDatabase command. The user must know that it also deletes the data files associated with it. It operates on the current database or let us say selected database.

MongoDB Drop Database

MongoDB Drop Database

a. List the Database

First of all, you should execute show dbs command to know if your database exists in MongoDB. For example,

> show dbs
local             0.52938GB
dataflair         0.49231GB
test              0.49231GB

We can see that we had created a database with the name “dataflair”. If your database exists, move to the next step.

Let’s Learn Advantages and Disadvantages of MongoDB

b. Check the Selected Database

You should make sure that you have selected the database you have to delete it. Run the db command in the command prompt to know the selected database.

>db
 Dataflair

In case you have not selected the right database, you should select that.

c. Select the Database

You should execute the “use” command as previously discussed.

>use dataflair
Switched to db dataflair

After doing that you can move to the next and final step.

d. Command for Drop Database

Here, “dropDatabase()” command is used for MongoDB drop database. It is executed on the selected database. 

>db. dropDatabase()
{ "dropped": "dataflair", "ok": 1}

It shows that the database has been deleted. You can also confirm by using “show dbs” command that will enlist the existing databases.

So, this was all about MongoDB Drop Database Tutorial. Hope you like our explanation.

Read about Important Features of MongoDB 

3. Conclusion

Hence, we have seen that how easy is that to create and drop the database in the MongoDB. MongoDB drop all database command deletes the data associated with the database which is deleted. Moving forward, we will see how to create a collection in MongoDB in the upcoming chapter. Furthermore, if you have any query, feel free to ask in the comment section.

For reference