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.
Contact Us