MongoDB Create Database

In this post, we will learn how to create a new database in MongoDB.

Table of Contents

Syntax

The syntax to create a new database is use keyword. Below is an example.

use YOUR_DATABASE_NAME

The above command will create a new database if the database doesn't exist. Otherwise, it will return the matching/existing database.

 

Example

To create a new database say blog. Use the below statement to create.

MongoDB > use blog

The above statement will print the following response

switched to db blog

Now if you write show dbs statement to display the recently created database.

MongoDB > show dbs

It won't show until you insert atleast one document in it. Below is the response

admin   0.000GB
config  0.000GB
local   0.000GB

Below is a statement to create a new document in blog database

MongoDB > db.post.insert({"title":"First blog post title", "description":"First blog post descripiton"})

The above query will create a new collection called post and insert one value. Below is the response of the above query.

WriteResult({ "nInserted" : 1 })

Now if you use show dbs it will list all the databases

If you want to check on which database you are using current. Use the below command

MongoDB > db
blog