...

/

Updating and Deleting Documents

Updating and Deleting Documents

Learn to update, add, and remove documents in MongoDB using the .updateOne(), .updateMany(), and .deleteOne() methods, along with operators like $set and $unset for modifying fields.

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:

Press + to interact
db.products.updateOne( query, update)

Here, query refers to a criterion that matches the document we want to ...