MongoDB Update Method Examples

In the following examples, we are working with:

  • Database: gfg
  • Collections: student
  • Document: Three documents contains name and the age of the students

Example 1:

Update the name of the document whose name key has avi value to hello world.

db.student.update({name:"avi"},{$set:{name:"helloword"}})

Here, the first parameter is the document whose value to be changed {name:”avi”} and the second parameter is set keyword means to set(update) the following matched key value with the older key value.

Note: The value of the key must be of the same datatype that was defined in the collection.

Example 2:

Update the age of the document whose name is prachi to 20.

db.student.update({name:"prachi"},{$set:{age:20}}

Here, the first parameter is the document whose value to be changed {name:”prachi”} and the second parameter is set keyword means to set(update) the value of the age field to 20.

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