MONGODB Tutorial



MongoDB UPDATING DOCUMENTS


🔧 MongoDB: Updating Documents

MongoDB allows you to update documents using methods like updateOne(), updateMany(), and replaceOne(). You can also use a variety of update operators like $set, $inc, and $unset to control how data is changed.

🔹 updateOne()

Updates the first document that matches the filter.

db.users.updateOne(
  { name: "John" },
  { $set: { age: 30 } }
)
  

🔹 updateMany()

Updates all documents that match the filter.

db.users.updateMany(
  { status: "inactive" },
  { $set: { status: "active" } }
)
  

🔹 replaceOne()

Replaces an entire document with a new one.

db.users.replaceOne(
  { name: "Alice" },
  { name: "Alice", age: 25, city: "Delhi" }
)
  

✨ Common Update Operators

  • $set – Set the value of a field
  • $inc – Increment a field by a value
  • $unset – Remove a field from the document
  • $rename – Rename a field
  • $mul – Multiply the value of a field
  • $min / $max – Only update if value is less/greater

🔹 Example with $inc and $unset

db.products.updateOne(
  { name: "Laptop" },
  {
    $inc: { stock: -1 },
    $unset: { discount: "" }
  }
)
  
Note: Always use update operators like $set unless you're using replaceOne(). Omitting them may overwrite the entire document.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review