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.

    db.collection.updateOne(filter, update, options)
  2. updateMany(): Updates multiple documents that match the specified filter.

    db.collection.updateMany(filter, update, options)

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:

use library_db

db.books.updateMany(
  { author: "Harper Lee" },
  { $set: { published_year: 1961 } }
)

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