Mongodb Guide

How to Update Data in MongoDB (updateOne, updateMany)

1. Definition

In MongoDB, data is updated using updateOne() and updateMany(). These methods modify existing documents in a collection based on specified conditions.

2. When to Use

  • Use updateOne() to update a single document
  • Use updateMany() to update multiple documents
  • When modifying user data, orders, or products
  • When building APIs with edit/update features

3. Where it is Used

  • Inside MongoDB collections
  • Backend applications (Node.js APIs)
  • CRUD operations (Update)
  • Admin dashboards and user management systems

4. Why We Use It

  • To modify existing data
  • To keep data up to date
  • To correct or change records
  • Supports both single and bulk updates

5. How It Works

  • Uses a filter to find matching documents
  • Uses update operators like $set
  • updateOne() updates the first matched document
  • updateMany() updates all matched documents

Basic Syntax

// updateOne()
db.users.updateOne(
  { name: "Manaswini" },
  { $set: { age: 23 } }
);

// updateMany()
db.users.updateMany(
  { role: "Developer" },
  { $set: { active: true } }
);

Real Example

// Update single user
db.users.updateOne(
  { name: "Manaswini" },
  { $set: { role: "Senior Developer" } }
);

// Update multiple users
db.users.updateMany(
  { role: "Developer" },
  { $set: { experience: "2+ years" } }
);

6. Explanation

  • updateOne() updates only one document
  • updateMany() updates multiple documents
  • $set is used to modify fields
  • Filter decides which documents to update

7. Advantages

  • Flexible updates
  • Supports bulk operations
  • Efficient and fast
  • Easy to modify specific fields

8. Disadvantages

  • Wrong filter can update unintended data
  • Requires careful query writing
  • No strict schema validation by default

Interview Points

  • updateOne() → updates first matched document
  • updateMany() → updates all matched documents
  • $set is commonly used update operator
  • Part of CRUD operations (Update)