MongoDB Update() Method Syntax

db.COLLECTION_NAME.update({SELECTION_CRITERIA}, {$set:{UPDATED_DATA}}, {
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>
})

Parameters:

  • SELECTION_CRITERIA: The selection filter for the update.
  • $set: Keyword to update the following specify document value.
  • UPDATED_DATA: New value that will replace the existing document.

Optional Parameters:

  • Upsert: When it is true it will make a new document in the collection when no document matches the given condition in the update method. The default value of this parameter is false.
  • multi: When it is true the update method update all the documents that meet the query condition. Otherwise, it will update only one document. The default value of this parameter is false.
  • writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
  • Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
  • arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array.
  • hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.

MongoDB – Update() Method

The update() method in MongoDB updates a document or multiple documents in the collection. When the document is updated the _id field remains unchanged.

This method can be used for a single updating of documents as well as multiple documents. By default, the db.collection.update() method updates a single document. To update all documents that match the given query. Include the option “multi: true“.

Note: In MongoDB, the update() method has been deprecated in favor of using updateOne() or updateMany() depending on your specific use case.

Similar Reads

MongoDB Update() Method Syntax

db.COLLECTION_NAME.update({SELECTION_CRITERIA}, {$set:{UPDATED_DATA}}, { upsert: , multi: , writeConcern: , collation: , arrayFilters: [ , ... ], hint: })...

MongoDB Update Method Examples

In the following examples, we are working with:...

Conclusion

The update method in MongoDB was used to update values in the MongoDB database. It updates documents in a collection. This method has now been deprecated and MongoDB has introduced new methods to update documents in a collection – updateOne() and updateMany()....

Contact Us