MongoDb - MongoDB Update Operators

MongoDB update operators are used in commands like:

  • updateOne()

  • updateMany()

  • findOneAndUpdate()

They help you modify documents efficiently without replacing them completely.

MongoDB Update Operators 

 

1. Field Update Operators

These operators modify document fields.

Operator Description Example
$set Sets a field to a specified value { $set: { status: "active" } }
$unset Removes a field { $unset: { status: "" } }
$rename Renames a field { $rename: { oldName: "newName" } }
$inc Increments a number { $inc: { views: 1 } }
$mul Multiplies a number { $mul: { price: 1.1 } }
$min Updates field only if new value is less { $min: { price: 200 } }
$max Updates field only if new value is greater { $max: { score: 95 } }
$currentDate Sets current date/time { $currentDate: { updatedAt: true } }

Example:

db.users.updateOne(
  { name: "John" },
  {
    $set: { status: "active" },
    $inc: { loginCount: 1 },
    $currentDate: { lastLogin: true }
  }
);

2. Array Update Operators

These operators modify array fields.

Operator Description Example
$push Adds element(s) to array { $push: { tags: "mongodb" } }
$push + $each Adds multiple elements { $push: { tags: { $each: ["atlas","charts"] } } }
$push + $sort Adds & sorts elements { $push: { scores: { $each: [90], $sort: -1 } } }
$addToSet Adds element only if it doesn’t exist { $addToSet: { tags: "database" } }
$pop Removes first (-1) or last (1) element { $pop: { tags: 1 } }
$pull Removes matching elements { $pull: { tags: "deprecated" } }
$pullAll Removes multiple specified values { $pullAll: { tags: ["old", "unused"] } }
$slice (with $push) Limits array size { $push: { logs: { $each: ["new"], $slice: -5 } } }
$position (with $push) Inserts at a specific index { $push: { tags: { $each: ["urgent"], $position: 0 } } }

Example:

db.posts.updateOne(
  { _id: 1 },
  {
    $push: {
      comments: {
        $each: ["Great post!", "Very helpful!"],
        $position: 0
      }
    }
  }
);

3. Array Positional Operators

These operators update specific elements inside arrays.

Operator Description Example
$ Updates first matching element { $set: { "scores.$": 95 } }
$[] Updates all elements { $inc: { "scores.$[]": 5 } }
$[<identifier>] Updates filtered elements { $inc: { "scores.$[high]": 10 } }
arrayFilters Defines conditions for $[] updates arrayFilters: [ { high: { $gte: 90 } } ]

Example — Update the first matching element:

db.students.updateOne(
  { _id: 1, scores: 80 },
  { $set: { "scores.$": 85 } }
);

Example — Update all elements:

db.students.updateOne(
  { _id: 1 },
  { $inc: { "scores.$[]": 5 } }
);

Example — Update only scores above 90:

db.students.updateOne(
  { _id: 1 },
  { $inc: { "scores.$[high]": 10 } },
  { arrayFilters: [ { high: { $gte: 90 } } ] }
);

4. Bitwise Update Operators

Used to manipulate bitwise values.

Operator Description Example
$bit Performs bitwise AND, OR, XOR { $bit: { flags: { and: 5 } } }

Example:

db.devices.updateOne(
  { _id: 1 },
  { $bit: { statusFlags: { or: 2 } } }
);

5. Combined Update Example

db.users.updateOne(
  { username: "alex" },
  {
    $set: { status: "premium" },
    $inc: { points: 50 },
    $push: { achievements: { $each: ["Gold", "Platinum"] } },
    $addToSet: { badges: "MongoDB Master" },
    $currentDate: { upgradedAt: true }
  }
);

6. Quick Summary Table

Category Operators
Field Updates $set, $unset, $rename, $inc, $mul, $min, $max, $currentDate
Array Updates $push, $push + $each, $addToSet, $pop, $pull, $pullAll, $slice, $position
Positional $, $[], $[identifier] + arrayFilters
Bitwise $bit

7. Best Practices

  • Always use updateOne() for single updates instead of updateMany() to avoid accidental changes.

  • Use $set instead of replacing the whole document.

  • Use $addToSet instead of $push to avoid duplicates.

  • Always create indexes for fields used in update filters.

  • Use arrayFilters for selective array updates for better performance.