CRUD
Update Operators
$set, $unset, $inc, $mul, $min, $max and $rename — the operators behind almost every update.
You almost never replace a document to change one field. You name an operator. These seven cover most scalar updates. Arrays have their own operators next.
db.users.updateOne(
{ email: "rahul@example.com" },
{
$set: { city: "Pune" },
$unset: { nickname: "" },
$inc: { age: 1 }
}
)- `$set` — write this value. Creates the field if it is missing.
- `$unset` — remove the field. The value you pass is ignored;
""is conventional. - `$inc` — add (or subtract with a negative). Missing numeric fields start at 0, then add.
db.products.updateOne(
{ name: "Mechanical Keyboard" },
{ $inc: { stock: -1 } }
)db.products.updateOne(
{ name: "Mechanical Keyboard" },
{
$mul: { price: 0.9 },
$min: { stock: 100 }
}
)db.users.updateOne(
{ email: "rahul@example.com" },
{ $max: { age: 28 } }
)
db.products.updateOne(
{ name: "Mechanical Keyboard" },
{ $rename: { qty: "stock" } }
)$min / $max only write when the new value is smaller / larger than what is stored. They are clamps, not 'set this number'. $rename fails if you try to rename onto a path that already exists — unset or pick another name.
Interview question
Why use $inc instead of reading a number and writing it back?
Two requests can read the same stock, both subtract, both write 19. $inc applies on the server in one atomic document update, so both sales land. I use $set for fields I already know; $inc for counters.
Interview question
What do $min and $max do on an update?
They only change the field if the new value is smaller ($min) or larger ($max) than the stored one. Updating with $min: { stock: 10 } does nothing if stock is already 5.