Tuesday, January 28, 2014

How to update or save document (Row) in MongoDB Collection (table)?

Today, we will explore how we can update document (row) in MongoDB. To update data we use UPDATE statement in RDBM system. We can update all the rows or only some row by applying WHER clause.

In MongoDB, we have two methods available to update document.
   1. update
   1. save

update() method

To update document (row) in MongoDB we can use following syntax:

db.collectionName.update(Selection_Criteria, New_data_value)

Let us see an example of update. We have Dept collection (table) and we are going to update the name of dept from "Global Finance" to "New Global Finance".

db.deptdetails.update({"_id" : ObjectId("52e711871a7cd793275359de")},{$set:{"DeptName":"New Global Finance"}})

We can apply multiple selection criteria in update statement.

db.deptdetails.update({DeptName : "Admin",DeptCode:50},{$set:{DeptName:"Admin",DeptCode:100}})

In the above statement we are updating DeptName and DeptCode.

By default the update () method updates only one document (Row). If you want to update the entire row which matches the selection criteria than you have to use multi parameter.

db.deptdetails.update({DeptName : "Admin",DeptCode:50},{$set:{DeptName:"Admin",DeptCode:100}},{multi:true})

save() method

save() method is used to replace the document(row). The entire document (row) along with columns will be replaced with the new data. The syntax for save() method is following:

db.collectionName.save({_id:ObjectId(),new_data})

For example we have following data in deptdetails collection (table)

{
    "_id" : ObjectId("52e711871a7cd793275359db"),
    "DeptName" : "Marketing",
    "DeptCode" : 30
}

We can issue the following command to change the entire content of this document (row)

db.deptdetails.save({"_id" : ObjectId("52e711871a7cd793275359db"),"mynewcol":" I am new data here"});

What is MongoDB?
How to get Started with MongoDB
How to create or drop Database in MongoDB?
How to create Collection (Table) in MongoDB?

Popular Posts

Real Time Web Analytics