MongoDB Create Database

In this article, we will see how to create a database in MongoDB. In MongoDB, Databases and collections are not usually explicitly created like in RDBMS(MySQL, Oralcle or Sybase,..). Like in RDBMS engines, CREATE DATABASE database_name wont work in NoSQL(MongoDB, Redis,..) engines.

use Command:
MongoDB use database_name is used to create database. The command will create a new database if it doesn’t exist, otherwise it will return the existing database.
Note: Use database_name command will creates a database. It will be not perminent until we create atleast one collection in the database.

MongoDB Create Database Syntax

use database_name

MongoDB Create Database Example:

If you want to use a database with name , then use DATABASE statement would be as follows −

> use r2schools switched to db r2schools

To check your currently selected database, use the command db

> db r2schools

If we want to check our databases list, use the command show dbs or show databases.

> show databases admin 0.014GB config 0.020GB local 0.276GB myDb 0.622GB

Our created database (r2schools) is not present in list. To display database, you need to insert at least one document into it.

With the below command, we are going to create a collection (books),if it exists, then adds a document to books collection.

>db.books.insert({"name":"r2schools"})

Now check the list of databases:

>show databases admin 0.014GB config 0.020GB local 0.276GB myDb 0.622GB r2schools 0.001GB

Note: In MongoDB, if we delete all collections from the database, then database will be dropped from MongoDB Server. So, database must contain atleast one collection.