Update Document in MongoDB

The update () method updates the values ​​in the existing Document while the save () method replaces the existing Document with the transmitted Document in that save () method.

The method update () or save () in MongoDB is used to update the Document into a Collection.

The update () method updates the values ​​in the existing Document while the save () method replaces the existing Document with the transmitted Document in that save () method.

Method of updating () in MongoDB

The update () method updates the values ​​in the existing Document.

Syntax

The basic syntax of update () method is as follows:

 > db . COLLECTION_NAME . update ( SELECTIOIN_CRITERIA , UPDATED_DATA ) 

For example

You monitor the Collection named mycol with the following data:

 { "_id" : ObjectId ( 5983548781331adf45ec5 ), "title" : "MongoDB Overview" } { "_id" : ObjectId ( 5983548781331adf45ec6 ), "title" : "NoSQL Overview" } { "_id" : ObjectId ( 5983548781331adf45ec7 ), "title" : "Tutorials Point Overview" } 

The following example will set the new 'New MongoDB Tutorial' header of the Document with the title 'MongoDB Overview':

 > db . mycol . update ({ 'title' : 'MongoDB Overview' },{ $set :{ 'title' : 'New MongoDB Tutorial' }}) > db . mycol . find () { "_id" : ObjectId ( 5983548781331adf45ec5 ), "title" : "New MongoDB Tutorial" } { "_id" : ObjectId ( 5983548781331adf45ec6 ), "title" : "NoSQL Overview" } { "_id" : ObjectId ( 5983548781331adf45ec7 ), "title" : "Tutorials Point Overview" } > 

By default, MongoDB will only update a single Document, to update multiple Documents, you set the 'multi' parameter to true.

 > db . mycol . update ({ 'title' : 'MongoDB Overview' },{ $set :{ 'title' : 'New MongoDB Tutorial' }},{ multi : true }) 

Save () method in MongoDB

The save () method replaces the existing Document with the new Document passed in this save () method.

Syntax

The basic syntax of the save () method is as follows:

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

For example

The following example will replace the Document with _id as '5983548781331adf45ec7'.

 > db . mycol . save ( { "_id" : ObjectId ( 5983548781331adf45ec7 ), "title" : "Tutorials Point New Topic" , "by" : "Tutorials Point" } ) > db . mycol . find () { "_id" : ObjectId ( 5983548781331adf45ec5 ), "title" : "Tutorials Point New Topic" , "by" : "Tutorials Point" } { "_id" : ObjectId ( 5983548781331adf45ec6 ), "title" : "NoSQL Overview" } { "_id" : ObjectId ( 5983548781331adf45ec7 ), "title" : "Tutorials Point Overview" } > 

According to Tutorialspoint

Previous article: Query Document in MongoDB

Next lesson: Delete Document in MongoDB

4 ★ | 1 Vote