Update MongoDB Records

MongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to update documents in a MongoDB collection. You will start by modifying a single document using the updateOne() method. Then, you will learn to modify multiple documents at once with the updateMany() method. You will also work with various update operators like $set, $inc, and $unset to perform specific modifications. Finally, you will explore the upsert option, which allows you to either update an existing document or create a new one if it does not exist. This lab provides a practical, hands-on approach to mastering fundamental data manipulation skills in MongoDB.

Updating a Single Document with updateOne

In this step, you will learn how to modify a single document in a MongoDB collection. We will use the updateOne() method along with the $set operator to change a field's value in a specific document.

First, open the MongoDB Shell to interact with your database.

mongosh

Once inside the shell, switch to the mylab_database that was prepared for you.

use mylab_database

Let's view the current documents in the books collection. The .pretty() method formats the output to make it more readable.

db.books.find().pretty();

You should see the three initial book documents. The _id values will be unique in your environment.

[
  {
    _id: ObjectId("..."),
    title: 'JavaScript Fundamentals',
    author: 'Mike Johnson',
    year: 2022,
    pages: 350
  },
  {
    _id: ObjectId("..."),
    title: 'Python Deep Dive',
    author: 'Sarah Williams',
    year: 2021,
    pages: 450
  },
  {
    _id: ObjectId("..."),
    title: 'Machine Learning Basics',
    author: 'John Doe',
    year: 2020,
    price: 39.99
  }
]

Now, let's update the publication year of the "JavaScript Fundamentals" book to 2023.

db.books.updateOne(
  { title: "JavaScript Fundamentals" },
  { $set: { year: 2023 } }
);

Let's break down this command:

  • updateOne(): This method finds the first document that matches the filter and updates it.
  • { title: "JavaScript Fundamentals" }: This is the filter document. It tells MongoDB to find a document where the title field is "JavaScript Fundamentals".
  • { $set: { year: 2023 } }: This is the update document. The $set operator replaces the value of the year field with 2023.

The command returns a result object that confirms the operation.

{
  "acknowledged": true,
  "insertedId": null,
  "matchedCount": 1,
  "modifiedCount": 1,
  "upsertedCount": 0
}

The matchedCount: 1 shows that one document matched our filter, and modifiedCount: 1 shows that one document was successfully updated.

To verify the change, find the document again.

db.books.findOne({ title: "JavaScript Fundamentals" });

The output will show the updated document with the new year.

{
  _id: ObjectId("..."),
  title: 'JavaScript Fundamentals',
  author: 'Mike Johnson',
  year: 2023,
  pages: 350
}

Updating Multiple Documents with updateMany

Sometimes you need to update several documents at once. For this, MongoDB provides the updateMany() method. In this step, you will add a new field to all books published before a certain year.

Let's add a status field with the value "Classic" to all books published before 2022.

db.books.updateMany({ year: { $lt: 2022 } }, { $set: { status: "Classic" } });

Here is an explanation of the command:

  • updateMany(): This method updates all documents that match the specified filter.
  • { year: { $lt: 2022 } }: This filter selects documents where the year is less than 2022. The $lt operator stands for "less than".
  • { $set: { status: "Classic" } }: This update document adds a new field status with the value "Classic" to all matched documents.

The output will show how many documents were matched and modified. In our case, two books were published before 2022.

{
  "acknowledged": true,
  "insertedId": null,
  "matchedCount": 2,
  "modifiedCount": 2,
  "upsertedCount": 0
}

To verify that both documents were updated, you can query for all books with the status "Classic".

db.books.find({ status: "Classic" }).pretty();

You will see the two books that now include the status field.

[
  {
    _id: ObjectId("..."),
    title: 'Python Deep Dive',
    author: 'Sarah Williams',
    year: 2021,
    pages: 450,
    status: 'Classic'
  },
  {
    _id: ObjectId("..."),
    title: 'Machine Learning Basics',
    author: 'John Doe',
    year: 2020,
    price: 39.99,
    status: 'Classic'
  }
]

Using More Update Operators: $inc and $unset

MongoDB offers a variety of operators for different kinds of updates. In this step, you will learn to use $inc to modify numerical values and $unset to remove fields from a document.

First, let's use the $inc operator to increase the page count of the "Python Deep Dive" book by 50. The $inc operator increments a field by a specified value.

db.books.updateOne({ title: "Python Deep Dive" }, { $inc: { pages: 50 } });

To confirm the change, retrieve the document.

db.books.findOne({ title: "Python Deep Dive" });

The pages field should now be 500 (450 + 50).

{
  _id: ObjectId("..."),
  title: 'Python Deep Dive',
  author: 'Sarah Williams',
  year: 2021,
  pages: 500,
  status: 'Classic'
}

Next, let's remove the price field from the "Machine Learning Basics" document. The $unset operator deletes a particular field. The value provided to $unset (in this case, "") does not matter and can be any value.

db.books.updateOne(
  { title: "Machine Learning Basics" },
  { $unset: { price: "" } }
);

Let's verify that the price field has been removed.

db.books.findOne({ title: "Machine Learning Basics" });

The output will show the document without the price field.

{
  _id: ObjectId("..."),
  title: 'Machine Learning Basics',
  author: 'John Doe',
  year: 2020,
  status: 'Classic'
}

Creating Documents with upsert

An "upsert" is a special type of update operation that either updates a document if it exists or inserts a new one if it does not. This is useful for avoiding separate "check-then-insert" logic and ensures atomicity in database operations. Upserts are particularly valuable in scenarios where you want to:

  • Ensure data consistency: Instead of first checking if a document exists and then deciding whether to insert or update, you can perform a single operation that handles both cases atomically
  • Handle concurrent operations: In multi-user environments, an upsert prevents race conditions where another process might insert the same document between your check and insert operations
  • Simplify application logic: Reduces the need for complex conditional logic in your application code, making it more maintainable and less error-prone

You can enable this behavior by adding the upsert: true option to your update command.

Let's try to add a new book, "Cloud Computing Essentials". Since this book does not exist in our collection, the upsert operation will create it.

db.books.updateOne(
  { title: "Cloud Computing Essentials" },
  { $set: { author: "David Lee", year: 2023, pages: 300 } },
  { upsert: true }
);

The command consists of three parts:

  1. The filter: { title: "Cloud Computing Essentials" }
  2. The update: { $set: { ... } }
  3. The options: { upsert: true }

Because no document matched the filter, a new one was created. The result object reflects this by including an upsertedId.

{
  acknowledged: true,
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1,
  upsertedId: ObjectId("...")
}

Now, let's run the same command again. This time, MongoDB will find the document we just created and update it.

db.books.updateOne(
  { title: "Cloud Computing Essentials" },
  { $set: { author: "David Lee", year: 2023, pages: 300 } },
  { upsert: true }
);

The result now shows matchedCount: 1. Since the data we are setting is the same as the existing data, modifiedCount is 0. If we had changed a value, modifiedCount would be 1.

{
  "acknowledged": true,
  "insertedId": null,
  "matchedCount": 1,
  "modifiedCount": 0,
  "upsertedCount": 0
}

You can verify that the new book exists in the collection.

db.books.findOne({ title: "Cloud Computing Essentials" });

The output will display the newly created document.

{
  _id: ObjectId("..."),
  title: 'Cloud Computing Essentials',
  author: 'David Lee',
  year: 2023,
  pages: 300
}

When you are finished, you can exit the MongoDB Shell.

exit;

Summary

In this lab, you have learned the essential techniques for updating documents in MongoDB. You practiced modifying single documents with updateOne and multiple documents with updateMany. You also explored powerful update operators, including $set to change field values, $inc to increment numbers, and $unset to remove fields. Finally, you learned how to use the upsert option to create a document if it doesn't already exist. These skills are fundamental for managing and maintaining data in any MongoDB application.