Database Create and Drop

In this lesson we will learn how to create and drop a Database in MongoDB.

Creating a Database

Open the command prompt and navigate to the /bin folder of the MongoDB using the cd command and execute the command mongod there. This will initiate the MongoDB server. We have to keep this command prompt window alive, as this is running MongoDB. To stop the MongoDB server, simply enter exit and press Enter.

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

Connect to MongoDB

In the command prompt window in which we ran the mongo command, after successfully connecting to the mongodb, just type the command the following :

use database_name

This will create a new database with the name database_name if there is no database already present with the same name. If a database already exists with the mentioned name, then it just connects to that database.

Use a Database in MongoDB

In the above picture, it creates a new database called mynewdatabase and will also connect to the same.

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

Checking active Database in MongoDB

To see the list of all the databases in MongoDB, use command show dbs

List all Databases in MongoDB

Please note that the newly created dstabase mynewdatabase has not been listed after running the above command. This is because, no records have been inserted into that database yet. Just insert one record and then run the command again as shown below :

List all Databases in MongoDB

To Insert data, run the following command. Dont worry about it, we will learn this in detail in next lessons.

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

NOTE : In MongoDB, test will be the default database. If no database is created, then all the data will be stored in the test database.

Drop a Database

First check the list of databases available as shown below, using the show dbs command.

List all Databases in MongoDB

If the newly created database mynewdatabase has to be dropped(deleted). Run the below command to delete the database. Before deleting the database, connect to the required database which is to be deleted.


Drop Database in MongoDB

Now again check the list of databases, to verify whether the database is deleted or not.

List all Databases in MongoDB

Note that the database mynewdatabase has been deleted and hence, it will not be listed in the list of the databases.