Update Document

update document in the collection through update() method. it works like update row into table in RDBMS.

Syntax:-

> db.collectionName.update({whereCondition},{newData});

In RDBMS:-

update tableName set field1='Value1',field2='Value2' where conditions

Example:-

> db.employees.update({name:"John"},{$set:{salary:200000}})

if document is updated then show message

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

If you want to update only one document in the collection then use updateOne() method.

Syntax:-

> db.collectionName.updateOne({whereCondition},{newData});

Example:-

 
> db.employees.updateOne({name:"Rom"},{$set:{salary:70000}})

after update successfully then show message

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

If you want to update multiple documents through one method then use updateMany() method.

Syntax:-

> db.collectionName.updateMany({whereCondition},{newData})

save() method is used to replace exists documents with the new document.

Syntax:-

> db.collectionName.save({whereCondition},{newData})