Updating Documents in MongoDB
Introduction
Welcome back to our course on MongoDB. In the previous lesson, we learned how to delete documents; now, we will explore how to update existing documents within our MongoDB database. We'll cover the updateOne() and updateMany() MongoDB methods. These methods are crucial because you'll often need to modify data in your database. For instance, a book in your collection might be re-categorized under a new genre, or an author's complete works might be republished in a different year. Let's dive in!
Two Ways to Update Data
MongoDB provides two primary methods for updating data in collections:
-
updateOne(): Updates the first document that matches the specified filter.
-
updateMany(): Updates multiple documents that match the specified filter.
In this course, we'll focus solely on the filter and update parameters. We'll cover the optional options parameter later in the course path.
Updating a Single Document
Updating Multiple Documents
To modify multiple documents simultaneously, the updateMany() method is used. Below is an example that updates the published_year of all books by "Harper Lee" to 1961 in the books collection:
In this example, { author: "Harper Lee" } is the filter, and { $set: { published_year: 1961 } } is the update. All book documents by Harper Lee will now have 1961 as their published_year.
