MongoDB Update Document

To update the documents in the collection through multiple methods like update(), updateOne(), updateMany() . 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:- Suppose, You have employees collection


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"salary" : 100000
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"salary" : 50000
	}
]

Now, you want to update employee salary where name is John.


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

if the document is updated then show a message

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

updateOne() method

this method is used to update only one document in the collection.

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 }

updateMany() method

This method is used to update multiple documents in the collection.

Syntax:-


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

save() method

This method is used to replace exists documents with the new document.

Syntax:-


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