here goes logo

How to create database in Mongodb

Creating database in Mongodb is simple but not very straightforward as you think. There is no such command called "create" in Mongodb, but a command "use".

> use database
switched to db database

Here we "use" a database with name "database" instead of "create" it. The command use actually didn't create the database, what it did is switch to the database by setting the shell variable "db", type command "show dbs" you will find there is no database created and type db to display the value of the shell variable:

> show dbs
local  0.000GB
> db

To get the database actually created, we need to write or save something into it. For example, create a collection or save a document.

A collection in Mongodb is similar to a table in SQL database, but it has no schema. Its actually just a bag of JSON objects.

Create a collection:

> db.createCollection("collection")
{ "ok" : 1 }
> show dbs
database  0.000GB
local     0.000GB
> show collections

Save a document, notice that if the collection is not exists, Mongodb will create for you when you save a document:

> {name: "Sam"} )
WriteResult({ "nInserted" : 1 })
> db.collection.find()
{ "_id" : ObjectId("582da705dc20967b55c71b12"), "name" : "Sam" }