0
0
MongoDBquery~5 mins

updateOne method in MongoDB

Choose your learning style9 modes available
Introduction
The updateOne method changes a single document in a collection. It helps keep data correct and up to date.
When you want to fix a typo in one user's name in a list.
When you need to change the status of one order from 'pending' to 'shipped'.
When you want to add a new phone number to one contact's details.
When you want to mark one task as completed in a to-do list.
When you want to update the price of one product in your store.
Syntax
MongoDB
db.collection.updateOne(
  <filter>,
  <update>,
  { upsert: <boolean> }
)
The finds the document to update.
The describes the changes to make, usually with $set to change fields.
Examples
Updates the age to 30 for the first user named Alice.
MongoDB
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 30 } }
)
Changes the status of order 123 to shipped without adding a new order if not found.
MongoDB
db.orders.updateOne(
  { orderId: 123 },
  { $set: { status: "shipped" } },
  { upsert: false }
)
Updates Bob's phone number or adds a new contact if none exists.
MongoDB
db.contacts.updateOne(
  { email: "bob@example.com" },
  { $set: { phone: "555-1234" } },
  { upsert: true }
)
Sample Program
First, we add a product named Pen. Then we update its price to 2.0. Finally, we check the product details.
MongoDB
db.products.insertOne({ name: "Pen", price: 1.5, stock: 100 })
db.products.updateOne(
  { name: "Pen" },
  { $set: { price: 2.0 } }
)
db.products.find({ name: "Pen" }).toArray()
OutputSuccess
Important Notes
updateOne changes only the first document that matches the filter.
If no document matches and upsert is true, a new document is created.
Use $set to change specific fields without replacing the whole document.
Summary
updateOne updates a single document matching a filter.
Use $set inside update to change fields safely.
upsert option adds a new document if none matches.