Update Operators

Update operators are used with `updateOne()`, `updateMany()`, or `findOneAndUpdate()` to modify documents without replacing them entirely.

1. Field Update Operators

OperatorDescriptionExample
$setSets the value of a field in a document.{ $set: { status: "A" } }
$unsetRemoves the specified field from a document.{ $unset: { status: "" } }
$incIncrements the value of the field by the specified amount.{ $inc: { views: 1 } }
$renameRenames a field.{ $rename: { "fname": "firstName" } }

2. Array Update Operators

These allow you to manipulate elements within an array field.

// $push: Add an item to an array
db.users.updateOne(
  { name: "John" },
  { $push: { tags: "electronics" } }
)

// $pull: Remove an item from an array
db.users.updateOne(
  { name: "John" },
  { $pull: { tags: "sale" } }
)

// $addToSet: Adds item only if it doesn't already exist (Prevents duplicates)
db.users.updateOne(
  { name: "John" },
  { $addToSet: { tags: "wireless" } }
)

3. $currentDate

Sets the value of a field to current date, either as a Date or a Timestamp.

db.users.updateOne(
  { name: "John" },
  { $currentDate: { lastModified: true } }
)
Pro Tip: Using `$inc` is much faster and safer than reading a value, incrementing it in your code, and saving it back (avoids race conditions).