Updating and Deleting Documents
Understand how to perform updates and deletions on MongoDB documents using methods like updateOne, updateMany, deleteOne, and deleteMany. Learn to add, modify, or remove fields and avoid common errors to manage dynamic data effectively.
Updating documents in MongoDB
In MongoDB, data is not static. Applications will often need to update existing data. For example, a user may change their email address, a product's price may need to be adjusted, or an order's status may change from "Pending" to "Shipped".
MongoDB provides the following two powerful methods to update data in a collection:
.updateOne(): Updates a single matching document.updateMany(): Updates all matching documents
Note: The scope of modifications made to the data in this lesson is confined to the executables only. The changes won't reflect elsewhere. We'll see variations of the
.find()method to read data after those modifications to notice the change.
The .updateOne() method
The .updateOne() method allows us to update only the first document that matches a given filter. It is perfect for situations where we only want to change a single record.
Syntax:
Here, query refers to a criterion that matches the ...