0
0
MongoDBquery~5 mins

Why advanced updates matter in MongoDB

Choose your learning style9 modes available
Introduction
Advanced updates help you change data in many ways at once, saving time and keeping your information correct.
When you want to change several fields in a document at the same time.
When you need to add or remove items from a list inside your data.
When you want to increase or decrease numbers without replacing the whole document.
When you want to update only parts of your data without losing other information.
When you want to update many documents quickly with one command.
Syntax
MongoDB
db.collection.updateOne(
  { filter },
  { update },
  { options }
)

// update can use operators like $set, $inc, $push, $pull
Use $set to change or add fields without replacing the whole document.
Use $inc to add or subtract numbers easily.
Examples
Change Alice's age to 30 without touching other data.
MongoDB
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 30 } }
)
Add 5 to Bob's score number.
MongoDB
db.users.updateOne(
  { name: "Bob" },
  { $inc: { score: 5 } }
)
Add 'reading' to Carol's list of hobbies.
MongoDB
db.users.updateOne(
  { name: "Carol" },
  { $push: { hobbies: "reading" } }
)
Remove 'swimming' from Dave's hobbies list.
MongoDB
db.users.updateOne(
  { name: "Dave" },
  { $pull: { hobbies: "swimming" } }
)
Sample Program
We add a product, then update its price, add stock, and add a new tag all at once.
MongoDB
db.products.insertOne({ name: "Pen", price: 10, tags: ["stationery"] })
db.products.updateOne(
  { name: "Pen" },
  {
    $set: { price: 12 },
    $inc: { stock: 5 },
    $push: { tags: "sale" }
  }
)
db.products.findOne({ name: "Pen" })
OutputSuccess
Important Notes
If a field does not exist, $inc creates it with the increment value.
Using multiple update operators in one command is efficient and safe.
Always test updates on sample data to avoid unwanted changes.
Summary
Advanced updates let you change many parts of your data in one step.
They help keep your data accurate and save time.
Operators like $set, $inc, $push, and $pull are key tools for updates.