Skip to main content
MongoDB
CHAPTER 08 Beginner

"Senior Dev" },

Updated: May 16, 2026
15 min read

# CHAPTER 8

Updating Documents in MongoDB

1. Introduction

Data is rarely static. Customers change their shipping addresses, blog posts get edited, and products go on sale. Modifying existing data is the U in CRUD (Update). In SQL, you use the UPDATE ... SET command. In MongoDB, updating data requires understanding two distinct components: the Filter (who to update) and the Update Operator (how to update them). In this chapter, we will master surgical data modification using updateOne(), updateMany(), and atomic operators.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the catastrophic danger of replacing documents accidentally.
  • Safely modify a single document using updateOne() and $set.
  • Modify multiple documents using updateMany().
  • Perform mathematical updates using $inc.
  • Understand the power of "Upserts" (Update or Insert).

3. The Structure of an Update Command

An update command takes two arguments:
  1. 1. The Filter: A query document finding the target (Exactly like find()).
  1. 2. The Modification: A document dictating the changes, utilizing special operators that begin with a $ dollar sign.

4. Updating a Single Document (updateOne())

If Alice gets a promotion and changes departments, we need to update her specific document. We use the $set operator to change the value of an existing field.
javascript
1234
db.employees.updateOne(
    { first_name: "Alice" }, // 1. The Filter (Find Alice)
    { $set: { department: "Management", salary: 110000 } } // 2. The Modification
)

Why $set is mandatory: If you forget $set and just write { department: "Management" }, older versions of MongoDB would literally delete Alice's entire document (erasing her name, age, and ID) and *replace* it with a tiny document containing only the word "Management". Always use $set to surgically alter specific fields without destroying the rest of the document!

5. Mathematical Updates ($inc)

What if you run a social media site, and a post gets a "Like"? You don't want to write complex PHP code to fetch the current likes (e.g., 5), add 1 to it (6), and then $set it to 6. MongoDB handles this natively with the $inc (Increment) operator. It mathematically adds or subtracts from a number directly inside the database.
javascript
1234567891011
// A user clicks "Like" on Post #42. Instantly add 1 to the likes counter!
db.posts.updateOne(
    { post_id: 42 }, 
    { $inc: { likes: 1 } } 
)

// A user uses a 5-point coupon. Subtract 5 points!
db.users.updateOne(
    { username: "john_doe" }, 
    { $inc: { loyalty_points: -5 } } 
)

6. Updating Multiple Documents (updateMany())

If the company decides to give a company-wide bonus of $5,000 to EVERYONE in the "Sales" department, we use updateMany(). It will find every matching document and apply the modification to all of them simultaneously.
javascript
1234
db.employees.updateMany(
    { department: "Sales" }, // Finds ALL Sales employees
    { $inc: { salary: 5000 } } // Adds $5000 to their current salary
)

7. The Magic of "Upserts"

An Upsert is a hybrid operation: "Update if it exists, Insert if it does not." Imagine a tracking system logging a user's total visits.
javascript
12345
db.website_stats.updateOne(
    { user_ip: "192.168.1.1" }, // Search for this IP
    { $inc: { visits: 1 } },    // Add 1 to visits
    { upsert: true }            // The Upsert Option!
)

The Magic: If this IP address has visited before, MongoDB finds the document and increments visits to 2. If this IP has *never* visited, the filter fails to find them. Because upsert: true is enabled, MongoDB automatically creates a brand new document from scratch, inserting the IP and setting visits to 1!

8. Mini Project: Product Inventory Management

Let's manage an E-commerce warehouse.
javascript
1234567891011121314151617
// 1. The price of the Laptop dropped. Update it!
db.products.updateOne(
    { name: "Laptop" },
    { $set: { price: 899 } }
)

// 2. A customer bought 3 Laptops. Reduce the inventory count mathematically!
db.products.updateOne(
    { name: "Laptop" },
    { $inc: { stock_quantity: -3 } }
)

// 3. Black Friday! Add a "on_sale" tag to EVERY product in the electronics category.
db.products.updateMany(
    { category: "Electronics" },
    { $set: { on_sale: true } }
)

9. Common Mistakes

  • Forgetting the $ Operators: Trying to update by writing db.users.updateOne({name: "John"}, {age: 30}) will fail in modern MongoDB (it expects an atomic operator). You must wrap the change in a $set or $inc object.
  • Using updateOne() for bulk changes: If you want to update all Active users, but you accidentally type updateOne({status: "Active"}, {$set: {verified: true}}), MongoDB will only update the very first Active user it finds, leaving the other 9,999 users unverified.

10. Best Practices

  • Atomic Operations are Safe: Using $inc is an "Atomic Operation". This means if 1,000 people click "Like" on a post at the exact same millisecond, MongoDB lines them up perfectly and processes them sequentially. The math will never be corrupted by race conditions.

11. Exercises

  1. 1. Write the command to update the status of all orders from "Pending" to "Shipped".
  1. 2. What does the $inc operator do when you pass it a value of -1?

12. MongoDB Challenges

Write an updateOne() command that searches for an employee named "David". It should use $set to change his title to "Senior Dev", and simultaneously use $inc to add 10000 to his salary. *(Hint: You can use multiple $ operators in the same update document!)*
javascript
1234567
db.employees.updateOne(
    { name: "David" },
    { 
        $set: { title: "Senior Dev" }, 
        $inc: { salary: 10000 } 
    }
)

13. MCQ Quiz with Answers

Question 1

What is the catastrophic risk of attempting to update a document WITHOUT using the $set operator in older drivers or the replaceOne() method?

Question 2

What is an "Upsert" operation in MongoDB?

14. Interview Questions

  • Q: Explain why a software engineer must use the MongoDB $inc operator for a "Page View Counter" rather than fetching the number in Node.js, adding 1 in JavaScript, and using $set to save it back.
  • Q: Describe the mechanical difference between updateOne() and updateMany().

15. FAQs

Q: How do I remove a specific field completely from a document? A: Instead of using $set, you use the $unset operator! {$unset: { obsolete_field: "" }} will physically delete that specific key-value pair from the document.

16. Summary

Modifying data in MongoDB is a surgical procedure. By separating your target filter from your modification operators, you can execute highly complex changes. Utilizing $set safely alters strings, $inc flawlessly manages mathematical counters, and upsert dramatically simplifies backend application logic.

17. Next Chapter Recommendation

We have mastered Creating, Reading, and Updating. There is only one CRUD operation left: Destroying data. In Chapter 9: Deleting Documents and Collections, we will learn how to permanently erase data using deleteOne, deleteMany, and drop.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·