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.

Let's start by opening the MongoDB shell:

mongosh

Switch to our previous database:

use mylab_database

First, let's ensure we have some books in our collection to work with:

db.books.insertMany([
    {
        title: "JavaScript Fundamentals",
        author: "Mike Johnson",
        year: 2022,
        pages: 350
    },
    {
        title: "Python Deep Dive",
        author: "Sarah Williams",
        year: 2021,
        pages: 450
    }
])

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" } finds the specific document
  • $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:

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.

First, let's start the MongoDB shell and ensure we're in the right database:

mongosh
use mylab_database

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

db.books.insertMany([
    {
        title: "Machine Learning Basics",
        author: "John Doe",
        year: 2020,
        price: 39.99
    },
    {
        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.

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.

First, let's start the MongoDB shell and ensure we're in the right database:

mongosh
use mylab_database

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()

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.

First, let's start the MongoDB shell and switch to our database:

mongosh
use mylab_database

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
const upsertResult = db.users.updateOne(
    { name: "David" },
    { $set: { name: "David", age: 25, status: "active" } },
    { upsert: true }
)

print("Upserted Document ID: " + upsertResult.upsertedId)

The output:

Upserted Document ID: ObjectId("64627c0a0d3d5a1a4c7c6a2b")

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

  • upsertedId: Contains the _id of the newly created document if an upsert occurs
  • This is useful when you want to insert a document if it doesn't exist
  1. Bulk Update Results
const bulkResult = db.users.updateMany(
    { status: "active" },
    { $inc: { age: 1 } }
)

print("Matched Active Users: " + bulkResult.matchedCount)
print("Modified Active Users: " + bulkResult.modifiedCount)

The output:

Matched Active Users: 2
Modified Active Users: 2

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.

First, let's start the MongoDB shell and switch to our database:

mongosh
use mylab_database

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