Updating Fields of document in MongoDB
MongoDB provides 4 key methods to update the document in the collection those are
sno Method Description 1 update() Either updates or replaces a single document that match a specified filter or updates all documents that match a specified filter. 2 updateMany() Update all documents that match a specified filter. 3 updateOne() Updates at most a single document that match a specified filter even though multiple documents may match the specified filter. 4 replaceOne() Replaces at most a single document that match a specified filter even though multiple documents may match the specified filter. - All the methods will have the same signature except method names and its return concept.
- Means except of update() method other methods will acknowledge response with objectId.
- So I am mentioning update() syntax
- Please refer Update Operators section in this tutorial for better understanding.
- Please refer WildCard/RegEx section in this tutorial for better understanding.
Syntax:db.collection.update( <query>, <update statement>, {upsert:<boolean>, multi: <boolean>, writeConcern: <document> })
NOTE:
- Upsert:true will creates a new document when no document matches the query criteria.
- If we don’t use Field update operators ($set,$inc..) update statement will be replaced with matched ones.