Create and Drop Database in MongoDB

 Welcome to a tutorial on how to create and drop a Database in MongoDB.

 

MongoDB: Creating a Database

To do this, open the command prompt and navigate to the /bin folder of the MongoDB using the cd command and execute the command mongod. After that, it will initiate the MongoDB server. You need to keep this command prompt window alive, as this is running MongoDB. But, to stop the MongoDB server, just enter exit and press Enter.

Afterward, open another command prompt and navigate to the /bin folder of the MongoDB again and execute the command mongo. Now, it will open up the client to run the MongoDB commands.


 

Now, in the command prompt window where ran the mongo command, after successfully connecting to the MongoDB, type the command below:

use database_name

So, it will create a new database with the name database_name if there is no database already present with the same name. But, if a database exists already with the mentioned name, then it's to connect to that database.


 

In the image above, we create a new database called mynewdatabase and will also connect to the same.

But, to check the currently connected database, type in db in the command prompt window, and you will get the name of the current database as result.

 

Now, to display the list of all the databases in MongoDB, use the command show dbs

 

Note that the newly created database mynewdatabase has not been listed after running the command above. It is so because no records have been inserted into that database. So, simply insert one record and then run the command again. This is shown below.

 

Run the command below to insert data. You will learn this command in subsequent tutorials.

db.student.insert({name : "Ada" })

Note that in MongoDB, the test will be the default database. Also, if a database is not created, then all the data will be stored in the test database.

 

MongoDB: Drop a Database

The first thing to do is to check the list of databases available by using the show dbs command. This is shown below.

 

Now, if the newly created database mynewdatabase has to be dropped (or deleted), run the below command to delete the database. But, before deleting the database, connect to the required database that will be deleted.

db.dropDatabase()

 

 

So, check the list of databases again, to verify if the database is deleted or not.

It is important to note that the database mynewdatabase has been deleted and, thus it will not be listed in the list of the databases.