Update operators are used with `updateOne()`, `updateMany()`, or `findOneAndUpdate()` to modify documents without replacing them entirely.
| Operator | Description | Example |
|---|---|---|
$set | Sets the value of a field in a document. | { $set: { status: "A" } } |
$unset | Removes the specified field from a document. | { $unset: { status: "" } } |
$inc | Increments the value of the field by the specified amount. | { $inc: { views: 1 } } |
$rename | Renames a field. | { $rename: { "fname": "firstName" } } |
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" } }
)Sets the value of a field to current date, either as a Date or a Timestamp.
db.users.updateOne(
{ name: "John" },
{ $currentDate: { lastModified: true } }
)