Tuesday, January 28, 2014

How to create Collection (Table) in MongoDB?

Today, I will share how we can create collection (table) in MonogoDB. Just like in Oracle, SQL Server or any other RDBMS, tables are created before storing data into them; we create Collection in MongoDB to store data.

In RDBMS you issue CREATE TABLE command along with Column names and their data types along with other constraints (Primary key, constraints etc.).

In MongoDB you define collection. You do not need to define column or their data type. In MongoDB each of the rows that you store can have different fields or columns. Unlike with RDBMS MongoDB gives you flexibility of dynamic columns. So for 1 row you may have 5 fields but for second row you can store 10 fields.

In MongoDB you can create collection by two methods. First you can use db.createCollection() method.

You can pass the collection name as a parameter.

db.createCollection(collection_name, options)

In below example, I have created table employeeList by issuing the db.createCollection(“employeeList”) command.

The second method is you can use the db.Collection_Name.Insert() command. The insert() method add a document in the collection. If Collection does not exist then it will create the collection.

To add a single document (row) into a collection (table) we can issue following command.

db.Collection_Name.Insert({Key1:Value1,Key2:Value2, ... KeyN:ValueN})

db.employeeList.insert({EmpName:"Sam Pitroda",Age:25,DOJ:04/04/2011,Salary:2695,Gender:"M"})

To add multiple documents (row), we can issue commands like this

db.employeeList.insert(
    {EmpName:"Anil Shastri",Age:39,DOJ:11/19/2007,Salary:4911,Gender:"M"},
    {EmpName:"Bill Rama",Age:33,DOJ:9/10/2006,Salary:4280,Gender:"M"},
    {EmpName:"John Butler",Age:23,DOJ:12/28/2009,Salary:2612,Gender:"M"},
    {EmpName:"Srini Arya",Age:36,DOJ:12/08/2006,Salary:2316,Gender:"F"} )

To see the list of Collections (tables) in the current database, we can use following command

show collections

What is MongoDB?
How to get Started with MongoDB
How to create or drop Database in MongoDB?

Popular Posts

Real Time Web Analytics