Introduction
Advanced updates help you change data in many ways at once, saving time and keeping your information correct.
db.collection.updateOne(
{ filter },
{ update },
{ options }
)
// update can use operators like $set, $inc, $push, $pulldb.users.updateOne(
{ name: "Alice" },
{ $set: { age: 30 } }
)db.users.updateOne(
{ name: "Bob" },
{ $inc: { score: 5 } }
)db.users.updateOne(
{ name: "Carol" },
{ $push: { hobbies: "reading" } }
)db.users.updateOne(
{ name: "Dave" },
{ $pull: { hobbies: "swimming" } }
)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" })$set and $inc in MongoDB?$set and $inc let you change specific fields without replacing the whole document.score by 5 in MongoDB?$inc operator is used to increase a numeric field by a specified amount.{ $inc: { score: 5 } }. Other options use wrong operators or syntax.{ _id: 1, tags: ["red", "blue"] }, what will be the result after running db.collection.updateOne({ _id: 1 }, { $push: { tags: "green" } })?$push operator adds an element to the end of an array field.db.collection.updateOne({ _id: 2 }, { score: 10 })$set to specify fields to change.{ score: 10 } directly without $set, causing an error.points by 10, add a new tag "vip" to their tags array only if it does not exist, and set their status to "active". Which update command achieves all this in one operation?$inc to add 10 to the points field.$addToSet adds an item to an array only if it doesn't already exist, perfect for tags.$set updates the status field to "active".Pass the test and this pattern moves unknown