How to create a new database in MongoDB?

MongoDBDatabaseBig Data Analytics

To create a new database in MongoDB, you need to use the ‘use’ command. The syntax is as follows:

use yourDatabaseName;

The above syntax will create a new database in MongoDB. If the database name is already present then it will return the database name. Here, I am going to create a database with the name ‘sample’.

The query to create a database in MongoDB is as follows -

> use sample;
switched to db sample

Now to check the present working database name you need to use the following syntax:

db

The query is as follows:

> db
sample

To list all database names in MongoDB, you need to use show command. The syntax is as follows:

show dbs;

The query is as follows:

> show dbs;

The following output all the databases:

admin 0.000GB
config 0.000GB
local 0.000GB

Look at the above sample output, there is no database name ‘sample’ which I have created already.

To show the sample database, you need to insert one document in sample database. The query to insert document is as follows:

> db.book.insert({"BookName":"Introduction to MongoDB"});
WriteResult({ "nInserted" : 1 })

Now you can list all the database name with the help of show command. The query is as follows:

> show dbs;

The following output now displays the ‘sample’ database we created above:

admin 0.000GB
config 0.000GB
local 0.000GB
sample 0.000GB

Look at the above sample output, the database ‘sample’ is present in the database list. In the above sample output, the user defined database is ‘sample’.

In this way, we can easily create a new database in MongoDB.

raja
Published on 18-Mar-2019 14:50:20
Advertisements