0
0
MongoDBquery~5 mins

Why updating documents matters in MongoDB

Choose your learning style9 modes available
Introduction

Updating documents lets you change information in your database without deleting and adding new data. This keeps your data accurate and current.

When a user's email address changes and you need to save the new one.
When you want to fix a typo in a product description.
When you need to mark an order as shipped after it is sent.
When you want to add a new phone number to a contact's details.
When you want to update the status of a task from 'pending' to 'done'.
Syntax
MongoDB
db.collection.updateOne(
  { <filter> },
  { $set: { <field1>: <value1>, ... } }
)

updateOne changes one document matching the filter.

$set changes only the specified fields without touching others.

Examples
Updates Alice's email address to a new one.
MongoDB
db.users.updateOne({ name: "Alice" }, { $set: { email: "alice@example.com" } })
Marks order 123 as shipped.
MongoDB
db.orders.updateOne({ orderId: 123 }, { $set: { status: "shipped" } })
Changes a contact's phone number.
MongoDB
db.contacts.updateOne({ phone: "123-456" }, { $set: { phone: "987-654" } })
Sample Program

This example adds a product, updates its price, then shows the updated product.

MongoDB
db.products.insertOne({ name: "Notebook", price: 10, stock: 100 })
db.products.updateOne({ name: "Notebook" }, { $set: { price: 12 } })
db.products.find({ name: "Notebook" }).pretty()
OutputSuccess
Important Notes

Updating only changes specified fields; other data stays safe.

If no document matches the filter, no update happens.

You can update multiple documents using updateMany instead of updateOne.

Summary

Updating documents keeps your data fresh and correct.

Use $set to change specific fields without losing other data.

Updating is faster and safer than deleting and adding new documents.