Skip to content

CRUD

Update Operators

$set, $unset, $inc, $mul, $min, $max and $rename — the operators behind almost every update.

IntermediateAbout 6 minutes

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 }
  }
)
Patch Rahul: set a field, drop one, bump age
  • `$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 } }
)
Stock after a sale. $inc is the safe increment — not read, add, write in Node.
db.products.updateOne(
  { name: "Mechanical Keyboard" },
  {
    $mul: { price: 0.9 },
    $min: { stock: 100 }
  }
)
$mul scales a number. $min writes only if the stored value is larger.
db.users.updateOne(
  { email: "rahul@example.com" },
  { $max: { age: 28 } }
)

db.products.updateOne(
  { name: "Mechanical Keyboard" },
  { $rename: { qty: "stock" } }
)
$max is a high-water mark. $rename fixes a field name.

$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?

Think about it first.

Interview question

What do $min and $max do on an update?

Think about it first.