MongoDB Tutorial
- Home
- Introduction
- Installation
- Connection & Databases
- CRUD Operations
- Comparison Operators
- Logical Operators
- Array Operators
- Evaluation Operators
- Update Operators
- Projection & Sorting
- Cursor Methods
- Querying Nested Docs
- Upserts & Indexes
- Aggregation Framework
- Data Modeling
- Validations & Transactions
- Geospatial Queries
- Advanced Indexing
- MongoDB with Next.js
- Best Practices
Update Operators
Update operators are used with `updateOne()`, `updateMany()`, or `findOneAndUpdate()` to modify documents without replacing them entirely.
1. Field Update Operators
| 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" } } |
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).