MongoDB - Update Document

MongoDB - Update Document

The MongoDB update() and save() methods are used to update a document into a collection. The update() method updates the values ​​in the existing document, while the save() method replaces the existing document with the document passed in the save() method.

MongoDB Update() Method

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

Syntax

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

>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)

example

Consider the collection mycol to have 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 title "New MongoDB Tutorial" to documents titled "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 one document. To update multiple documents, you need to set the "multi" parameter to true.

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

MongoDB Save() Method

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

Syntax

The basic syntax of MongoDB save() method is shown below −

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

example

The following example will replace the document with _id '5983548781331adf45ec5'.