Tuesday, January 28, 2014

How to add document (Row) in MongoDB Collection (table)?

In this post we will see how we can add new documents (rows) into MongoDB Collection (table). MongoDB is a document oriented NoSQL database. The terminology of NoSQL is different from RDBMS such as Oracle, DB2, Ms-SQL Server.

A MongoDB collection is equivalent to RDBMS table. Document in MongoDB is equivalent to Rows into RDBMS.

To add a new row in MongoDB collection we use the insert() method. The syntax for the same is

db.CollectionName.insert({key:value,key2:value2,keyN:valueN})

The below example will create a database named “Dept”. A Collection “deptdetails” will be created and we will add document(Row).

use dept
switched to db dept
db.createCollection("deptdetails")
{ "ok" : 1 }
db.deptdetails.insert({DeptName:"Sales",DeptCode:10})
db.deptdetails.find().pretty()
{
 nbsp;nbsp; "_id" : ObjectId("52e6da801a7cd793275359d3"),
nbsp;nbsp;nbsp; "DeptName" : "Sales",
nbsp;nbsp;nbsp; "DeptCode" : 10
}

If you want to add multiple documents (rows) at one time you can follow the below syntax:

db.CollectionName.insert(
[
    {key:value,key2:value2,keyN:valueN},
    {key:value,key2:value2,keyN:valueN},
    {key:value,key2:value2,keyN:valueN}
]
)

db.deptdetails.insert(
[{DeptName:"HR",DeptCode:20},
{DeptName:"Marketing",DeptCode:30},
{DeptName:"IT",DeptCode:40},
{DeptName:"Admin",DeptCode:50},
{DeptName:"Global Finance",DeptCode:60}]
)

In MongoDB if you want to read about the stats of a collection you can issue db.CollectionName.stats() command. This will show the collection size, number of documents (row), average object size, index size of the collection.

What is MongoDB?
How to get Started with MongoDB
How to create or drop Database in MongoDB?
How to create Collection (Table) in MongoDB?
How to update or save document (Row) in MongoDB Collection (table)?

Popular Posts

Real Time Web Analytics