Update document - MongoDB


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

1- update() method replaces the existing value of the existing documents in MongoDB collection.

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

MongoDB Update() method
When we want to update the 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 the existing data in the 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"}


The 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 the only a 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 the 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"}
> 

2 comments:

Please do not enter any spam link in the comment box.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...