Jul 4, 2015

Update document - MongoDB

To update document of MongoDB collection we can use update() and save() methods.

1- update() method replace the existing value of existing document in MongoDB collection.

2- save() method replace the existing document with passed document in MongoDB collection.

MongoDB Update() method
When we want to update existing value of document then we have to use update() method.

SYNTAX:
Basic syntax of update() method is given below:


>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)


EXAMPLE:
Below is existing data in collection.


{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview", "by":"codefari.com"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"ASP.Net Over view", "by":"codefari.com"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"SQL Server 2014", "by":"codefari.com"}


Below given example will set the new title 'New MongoDB overview by  dilip' with existing title 'MongoDB Overview'


>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'MongoDB overview and documentation'}})




>db.mycol.find()

{ "_id" : ObjectId(5983548781331adf45ec5), "title":" MongoDB overview and documentation", "by":"codefari.com"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"ASP.Net Over view", "by":"codefari.com"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"SQL Server 2014", "by":"codefari.com"}
> 


To update multiple we need to set a parameter 'multi' to true because by default MongoDB collection will update only single document.

>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':' MongoDB overview and documentation '}},{multi:true})


MongoDB Save() Method
Replaces the existing document with the new document passed in save () method.

SYNTAX:
Below is given basic syntax of MongoDB Collection save() method:


>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})



EXAMPLE:
Following example will replace the document with the _id '5983548781331adf45ec7'


>db.mycol.save(
   {
      "_id" : ObjectId(5983548781331adf45ec7), "title":"MongoDB with elastic search"
   }
)



>db.mycol.find()

{ "_id" : ObjectId(5983548781331adf45ec5), "title":" MongoDB with elastic search "}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"ASP.Net Over view", "by":"codefari.com"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"SQL Server 2014", "by":"codefari.com"}
>