Create Database

Use Database method:

There is no create database command in MongoDB. Actually, MongoDB do not provide any command to create database.

It may be look like a weird concept, if you are from traditional SQL background where you need to create a database, table and insert values in the table manually.

Here, in MongoDB you don't need to create a database manually because MongoDB will create it automatically when you save the value into the defined collection at first time.

You also don't need to mention what you want to create, it will be automatically created at the time you save the value into the defined collection.

Note
Here one thing is very remarkable that you can create collection manually by "db.createCollection()" but not the database.

How and when to create database

If there is no existing database, the following command is used to create a new database.

Syntax:

snippet
use DATABASE_NAME

If the database already exists, it will return the existing database.

Let' take an example to demonstrate how a database is created in MongoDB. In the following example, we are going to create a database "rookienerddb".

See this example

snippet
>use rookienerddb
Output
Swithched to db rookienerddb

To check the currently selected database, use the command db:

snippet
>db
Output
rookienerddb

To check the database list, use the command show dbs:

snippet
>show dbs
Output
local 0.078GB

Here, your created database "rookienerddb" is not present in the list, insert at least one document into it to display database:

snippet
>db.movie.insert({"name":"rookienerd"})
Output
WriteResult({ "nInserted": 1})
snippet
>show dbs
Output
rookienerddb 0.078GB local 0.078GB
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +