R
Rishtaara
MongoDB Fundamentals
Lesson 21 of 40Article18 min

Field Update Operators

When you update a MongoDB document, you rarely replace the whole document. Instead you use field update operators — instructions that say 'change this field, leave everything else alone.'

Field Update Operators — overview

When you update a MongoDB document, you rarely replace the whole document. Instead you use field update operators — instructions that say 'change this field, leave everything else alone.'

All field update operators start with $. They go inside the second argument of updateOne, updateMany, or findOneAndUpdate.

Real-life example: Field update operators are like sticky notes on a student file — 'raise grade to 11', 'add ₹50 to wallet balance' — without rewriting the entire file from scratch.

  • $set — assign or overwrite a field value
  • $unset — remove a field entirely
  • $inc — add or subtract a number
  • $mul — multiply a number field
  • $min / $max — keep the smaller or larger value
  • $rename — change a field name
Never pass a plain object like { price: 999 } in an update — that replaces the whole document. Always wrap changes in operators like { $set: { price: 999 } }.

$set — the workhorse

$set assigns a value to a field. If the field does not exist, MongoDB creates it. You can set nested fields with dot notation.

Real-life example: $set is like filling in a blank on a form — name, email, or nested address.city — without touching other boxes.

$set on nested fields and mixed types
// Update a student's grade and city
db.students.updateOne(
  { email: "asha@rishtaara.edu" },
  {
    $set: {
      grade: 11,
      "address.city": "Mumbai",
      updatedAt: new Date()
    }
  }
)

// Set a new field on a product
db.products.updateOne(
  { sku: "MOUSE-01" },
  { $set: { featured: true, badge: "Editor's Choice" } }
)

$unset — remove fields

$unset deletes a field from a document. Pass an empty string, 1, or true as the value — the value itself is ignored; only the field name matters.

Real-life example: $unset is like redacting a line from a record — the rest of the document stays intact.

Remove deprecated or sensitive fields
// Remove a temporary promo flag after sale ends
db.products.updateMany(
  { promoEndsAt: { $lt: new Date() } },
  { $unset: { promoCode: "", discountPercent: "" } }
)

// GDPR-style: remove optional phone if user opts out
db.users.updateOne(
  { _id: userId },
  { $unset: { phone: "" } }
)

$inc and $mul — numeric changes

$inc adds (or subtracts with a negative number) to a numeric field. If the field is missing, MongoDB treats it as zero before applying the increment.

$mul multiplies a field by a number. Useful for percentage discounts or currency conversion.

Real-life example: $inc is a shop till — each sale adds +1 to stock sold and −1 from inventory. $mul is a 10% off sticker that multiplies price by 0.9.

$inc only works on numeric fields. Trying to $inc a string field throws an error.
Inventory and loyalty points
// Customer buys 2 units — decrease stock, bump sales counter
db.products.updateOne(
  { sku: "NOTEBOOK-A5" },
  {
    $inc: { stock: -2, unitsSold: 2 },
    $set: { updatedAt: new Date() }
  }
)

// Apply 15% discount to all clearance items
db.products.updateMany(
  { category: "clearance" },
  { $mul: { price: 0.85 } }
)

// Add loyalty points after order
db.users.updateOne(
  { _id: userId },
  { $inc: { loyaltyPoints: 50 } }
)

$min and $max — keep extremes

$max updates a field only if the new value is greater than the current value. $min updates only if the new value is smaller.

These are perfect for leaderboards, high-water marks, and price floors without a read-modify-write race.

Real-life example: $max on a high score is like a trophy case — only a better score replaces what's on display. $min on price is a 'never below ₹99' rule.

Leaderboard and price floor
// Only update if new score beats the old one
db.players.updateOne(
  { username: "RahulX" },
  { $max: { highScore: 12500 } }
)

// Ensure sale price never drops below cost floor
db.products.updateOne(
  { sku: "LAMP-LED" },
  { $min: { salePrice: 1499 } }
)

// Track lowest recorded temperature for a sensor
db.sensors.updateOne(
  { sensorId: "TEMP-01" },
  { $min: { minCelsius: -2.4 } }
)

$rename — change field names

$rename moves data from one field name to another. If the target name already exists, $rename overwrites it.

Use during schema migrations when you rename phone to mobile across many documents.

Real-life example: $rename is relabelling folders in a filing cabinet — 'phone' becomes 'mobile' without copying the papers by hand.

On Rishtaara practice projects, always set updatedAt with $set whenever you $inc stock or change prices — your future self will thank you during debugging.
Schema migration with $rename
// Rename field across all users
db.users.updateMany(
  {},
  { $rename: { phone: "mobile" } }
)

// Combine rename with $set for a clean migration
db.students.updateMany(
  { legacyId: { $exists: true } },
  {
    $rename: { legacyId: "externalId" },
    $set: { migratedAt: new Date() }
  }
)