Wednesday, June 01, 2011

Creating a new database in MongoDB

When you start with MongoDB it might be beneficial to not have any experience with databases in some cases as MongoDB is just handling things and approaching things in a different way. Within for example Oracle we are used to having schema, a table, records and columns. Within MongoDB you have to forget all of this as they are not working with a schema or a table. The best you can describe a schema within MongoDB is the concept of a "database" in mongo in which you will store things.

So when you are working with MongoDB you have to learn how you can work with databases, create them and switch between the different databases. When you login to a MongoDB you most likely would like to know which databases are currently in MongoDB. To get a list of all databases you can use "show dbs"

> show dbs
admin (empty)
callreg 0.0625GB
local (empty)
test 0.0625GB
>

local, test and admin are installed by default, the callreg database is something I created to do some testing. If you want to switch between one database and another you can use the command "use " for example if we want to switch to the callreg database you can use the command "use callreg".

> use callreg
switched to db callreg
>

Now lets say we want to create a new database specially for handling shipping data, we will name it shipping. Basically you do not create a database within MongoDB as such. you can just switch to the (not yet existing) database by using the command "use shipping". This will bring you to the database shipping. Now if we insert data into this database it will be directly created. In the below example you see that we switch to the shipping database (which is not existing yet) and insert a document.

> use shipping
switched to db shipping
>
>
> db.shipping.insert({"shipping_number" : "1045", "receivedate" : "12-FEB-2011"})
>

if we nog check the list of databases using the "show dbs" command you will see that the database is created.

> show dbs
admin (empty)
callreg 0.0625GB
local (empty)
shipping 0.0625GB
test 0.0625GB
>

This is how you quickly create a new database, switch to the database (even if is not yet existing) and insert something into the database.

5 comments:

julian said...

Thanks for the quick reference.

Thamizhannal said...

great one!. one question here
> db.shipping.insert({"shipping_number" : "1045", "receivedate" : "12-FEB-2011"})
Here, Is shipping is db name?. If yes. then on what table does this row gets inserted? Or what is table name?

Thamizhannal said...

> db.shipping.insert({"shipping_number" : "1045", "receivedate" : "12-FEB-2011"})
Here in db.shipping.insert command. Is shipping is db name Or table name?

Nikhil said...

Shipping is table name.

Anonymous said...

how to create a 100GB database for mongodb