Update MongoDB Records

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to update MongoDB records using various techniques, including updating a single document, performing bulk updates, and utilizing update operators. You will also explore how to handle update results and verify the updated data. This lab covers the fundamental CRUD (Create, Read, Update, Delete) operations in MongoDB, equipping you with the necessary skills to effectively manage your data in a MongoDB database.

The lab starts by demonstrating how to update a single document using the updateOne() method, followed by exploring bulk updates with the updateMany() method. You will then dive into using update operators, such as $set, to modify specific fields within documents. Additionally, you will learn how to handle the update results and verify the updated data to ensure the integrity of your MongoDB records.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/DataTypesGroup(["`Data Types`"]) mongodb(("`MongoDB`")) -.-> mongodb/ErrorHandlingGroup(["`Error Handling`"]) mongodb/BasicOperationsGroup -.-> mongodb/insert_document("`Insert Document`") mongodb/BasicOperationsGroup -.-> mongodb/update_document("`Update Document`") mongodb/BasicOperationsGroup -.-> mongodb/bulk_update_documents("`Bulk Update Documents`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/DataTypesGroup -.-> mongodb/manage_array_elements("`Manage Array Elements`") mongodb/ErrorHandlingGroup -.-> mongodb/handle_write_errors("`Handle Write Errors`") subgraph Lab Skills mongodb/insert_document -.-> lab-420823{{"`Update MongoDB Records`"}} mongodb/update_document -.-> lab-420823{{"`Update MongoDB Records`"}} mongodb/bulk_update_documents -.-> lab-420823{{"`Update MongoDB Records`"}} mongodb/find_documents -.-> lab-420823{{"`Update MongoDB Records`"}} mongodb/query_with_conditions -.-> lab-420823{{"`Update MongoDB Records`"}} mongodb/manage_array_elements -.-> lab-420823{{"`Update MongoDB Records`"}} mongodb/handle_write_errors -.-> lab-420823{{"`Update MongoDB Records`"}} end

Update Single Document

In this step, you'll learn how to update a single document in MongoDB using the updateOne() method. We'll continue working with our book collection and demonstrate how to modify specific document attributes.

First, let's connect to the MongoDB shell and switch to the mylab_database database:

mongosh
use mylab_database

To begin, let's check the current books in our collection:

db.books.find()

You should see the list of books we added earlier:

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

Now, we'll use the updateOne() method to modify a specific document. We'll update the book "JavaScript Fundamentals" to change its page count:

db.books.updateOne(
    { title: "JavaScript Fundamentals" },
    { $set: { pages: 400 } }
)

Let's break down this command:

  • The first argument { title: "JavaScript Fundamentals" } is the filter that finds the specific document to update.
  • $set is an update operator that changes the value of a specific field.
  • { pages: 400 } sets the new page count to 400.

To verify the update, we'll find the document again:

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

You should see the document with the updated page count of 400.

Perform Bulk Updates

In this step, you'll learn how to perform bulk updates in MongoDB using the updateMany() method. Bulk updates are powerful when you need to modify multiple documents that match a specific condition.

Let's add some more books to our collection to demonstrate bulk updates:

db.books.insertMany([
    {
        title: "Advanced Python",
        author: "John Doe",
        year: 2019,
        price: 44.99
    },
    {
        title: "Data Science Handbook",
        author: "Jane Smith",
        year: 2021,
        price: 49.99
    }
])

Now, let's perform a bulk update to increase the price of all books by John Doe by $10:

db.books.updateMany(
    { author: "John Doe" },
    { $inc: { price: 10 } }
)

Breaking down this command:

  • { author: "John Doe" } selects all books by John Doe.
  • $inc is an update operator that increments the specified field.
  • { price: 10 } increases the price by 10.

Verify the update by finding all books by John Doe:

db.books.find({ author: "John Doe" })

You should see that the prices for "Machine Learning Basics" and "Advanced Python" have increased by $10.

Let's do another bulk update by adding a category to all books published before 2021:

db.books.updateMany(
    { year: { $lt: 2021 } },
    { $set: { category: "Older Publication" } }
)

Here, $lt means "less than", updating all books published before 2021 by adding a "Older Publication" category.

Use Update Operators

In this step, you'll explore powerful MongoDB update operators that allow you to perform complex document modifications beyond simple value changes.

Let's first create some sample data to work with:

db.products.insertMany([
    {
        name: "Laptop",
        price: 1000,
        tags: ["electronics", "computer"],
        stock: 50
    },
    {
        name: "Smartphone",
        price: 800,
        tags: ["electronics", "mobile"],
        stock: 30
    }
])

MongoDB provides several powerful update operators that allow you to modify documents in sophisticated ways:

  1. $mul Operator - Multiply Numeric Values
db.products.updateOne(
    { name: "Laptop" },
    { $mul: { price: 1.1 } }
)

The output:

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

The $mul operator multiplies the value of a field by the specified number. In this example, we're increasing the laptop's price by 10%.

  1. $push Operator - Add Elements to an Array
db.products.updateOne(
    { name: "Smartphone" },
    { $push: { tags: "sale" } }
)

The output:

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

The $push operator adds an element to an array field. Here, we're adding a "sale" tag to the smartphone's tags.

  1. $min and $max Operators - Update Based on Comparison
db.products.updateOne(
    { name: "Laptop" },
    {
        $min: { stock: 40 },
        $max: { price: 1200 }
    }
)

The output:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0,
  upsertedId: null
}
  • $min updates the field if the specified value is less than the existing value
  • $max updates the field if the specified value is greater than the existing value

Let's verify our updates:

db.products.find()
[
  {
    _id: ObjectId('674683aebec38876f7c1c18e'),
    name: 'Laptop',
    price: 1200,
    tags: [ 'electronics', 'computer' ],
    stock: 40
  },
  {
    _id: ObjectId('674683aebec38876f7c1c18f'),
    name: 'Smartphone',
    price: 800,
    tags: [ 'electronics', 'mobile', 'sale' ],
    stock: 30
  }
]

You should see the modified documents with updated prices, tags, and stock levels.

Handle Update Results

In this step, you'll learn how to handle and interpret the results of update operations in MongoDB. Understanding update results helps you verify that your updates were successful and understand their impact.

Let's create some sample data to work with:

db.users.insertMany([
    { name: "Alice", age: 28, status: "active" },
    { name: "Bob", age: 35, status: "inactive" },
    { name: "Charlie", age: 42, status: "active" }
])

Now, let's explore different update result properties:

  1. Basic Update Result
const result = db.users.updateOne(
    { name: "Alice" },
    { $set: { age: 29 } }
)

print("Matched Documents: " + result.matchedCount)
print("Modified Documents: " + result.modifiedCount)

The output:

Matched Documents: 1
Modified Documents: 1

The result object provides two key properties:

  • matchedCount: Number of documents that match the filter
  • modifiedCount: Number of documents actually modified

This helps you understand exactly what happened during the update operation. If matchedCount is 0, no documents were found. If modifiedCount is 0, no changes were made even if a document was matched.

  1. Upsert Operation
db.users.updateOne(
    { name: "David" },
    { $set: { name: "David", age: 25, status: "active" } },
    { upsert: true }
)

An upsert creates a new document if no matching document is found:

  1. Bulk Update Results
db.users.updateMany(
    { status: "active" },
    { $inc: { age: 1 } }
)

This demonstrates how to get results from a bulk update operation, showing how many active users were matched and modified.

Let's verify our updates:

db.users.find()

Verify Updated Data

In this step, you'll learn various methods to verify and query updated data in MongoDB. Confirming your updates is crucial for maintaining data integrity and ensuring your modifications are applied correctly.

Let's create some sample data to explore verification techniques:

db.inventory.insertMany([
    {
        item: "laptop",
        quantity: 25,
        status: "available",
        category: "electronics"
    },
    {
        item: "smartphone",
        quantity: 15,
        status: "low stock",
        category: "mobile"
    }
])
  1. Exact Match Query for Precise Verification
db.inventory.updateOne(
    { item: "laptop" },
    { $set: { quantity: 30 } }
)

const laptopUpdate = db.inventory.findOne({
    item: "laptop",
    quantity: 30
})

print("Laptop Update Verified: " + (laptopUpdate !== null))

The output:

Laptop Update Verified: true

This method checks if a document exists with exactly the updated values. It's the most direct way to confirm a specific update.

  1. Range-Based Verification
db.inventory.updateMany(
    { status: "low stock" },
    { $inc: { quantity: 5 } }
)

const updatedItems = db.inventory.find({
    quantity: { $gte: 20 }
}).toArray()

print("Updated Low Stock Items: " + updatedItems.length)

The output:

Updated Low Stock Items: 2

Using comparison operators like $gte (greater than or equal to) allows you to verify updates across multiple documents.

  1. Complex Query Verification
db.inventory.updateOne(
    { item: "smartphone" },
    { $set: { status: "in stock" } }
)

const verifyUpdate = db.inventory.findOne({
    item: "smartphone",
    status: "in stock",
    category: "mobile"
})

print("Smartphone Status Updated: " + (verifyUpdate !== null))

The output:

Smartphone Status Updated: true

This demonstrates a more complex verification that checks multiple conditions simultaneously.

Let's view all documents to confirm our updates:

db.inventory.find()

Summary

In this lab, you learned how to update single and multiple documents in a MongoDB database. You started by using the updateOne() method to modify a specific document, changing the page count of the "JavaScript Fundamentals" book. You then explored performing bulk updates with the updateMany() method, allowing you to modify multiple documents that match a specific condition. Additionally, you learned about various update operators, such as $set, which you used to change field values. Finally, you verified the updated data to ensure the changes were successfully applied.

Other MongoDB Tutorials you may like