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:

  1. updateOne(): Updates the first document that matches the specified filter.

  2. 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

With the updateOne() method, you can modify a single document in a collection based on a filter. Here is an example where we update the genre of "Moby Dick" from 'Novel' to 'Classic' in the books collection:

In this example, { title: "Moby Dick" } is the filter that targets the document with the title "Moby Dick", and { $set: { genre: "Classic" } } is the update that changes the genre to "Classic".

The $set operator is used to specify the fields to update. It replaces the value of a field with the specified value, and if the field does not exist, $set will create it. There are other update operators such as $inc (increment), $rename (rename a field), and $unset (remove a field). These operators provide more flexibility in updating documents. We will cover them in a dedicated course titled "A Closer Look at Update Operations" in the course path.

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.

Summary

In this lesson, we covered the basics of updating data in MongoDB collections. You learned how to use the updateOne() method to update a single document and the updateMany() method to update multiple documents. These operations are essential for properly maintaining and managing your database. Get ready to practice these concepts in the upcoming exercises!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal