MongoDB: Create Database
Before we store data as documents or work on them, we first need to create a database.
In MongoDB, a database consists of collections; a collection in turn is a grouping of documents. A collection can only exist within one database.
Now if you are using a Mac, open your terminal and start the Mongo Daemon first.
$ mongod
Next, open a new terminal and start the Mongo Shell.
$ mongo
If you are using Windows, go to the /bin
directory and double-click on the Mongo Daemon mongod.exe
. And in the same /bin
directory, double-click on mongo.exe
next. This is the Mongo Shell from where you will be entering commands.
Now there are a few default databases in MongoDB, like admin
, config
and local
. We will list all the databases with the following command
$ show databases
or
$ show dbs
You will find the admin
, config
and local
databases listed by default.
Now unlike in SQL, there is no straight-forward command as "CREATE DATABASE"
to create a database in MongoDB. To create a database in MongoDB, we first need to switch to it using the use
command, and later add at least one record (document) to a collection in it.
Suppose we intend to create a database called books
. Switch to it first using the use
command.
$ use books
The number of characters in a database name should be less than 64 characters.
Now the above use
command does not merely create a database. If you run
$ show databases
you will find that your newly "created" books
database is not in the list. You need to store at least one document in a collection.
We will create a new collection called comics
and will insert the details of the following comic book as a document into it: Planet Comics, No. 55 published on July, 1948.
$ db.comics.insert({
no: 55,
title: 'Planet Comics',
year: 1948
})
Now if you list all databases again,
$ show dbs
you will find the new database books
listed.