Updating and Deleting Documents
Explore how to efficiently update and delete documents in MongoDB. Learn to use updateOne and updateMany for modifying single or multiple records, add or remove fields with $set and $unset operators, and delete documents with deleteOne and deleteMany methods. Understand common mistakes to avoid when managing MongoDB documents.
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 document we want to ...