Loading lessons...
Field Update Operators
Field Update Operators
Update operators modify documents during updateOne() and updateMany(). These change individual fields.
The field operators
| Operator | Meaning |
|---|---|
| $currentDate | Sets a field to the current date |
| $inc | Increments a numeric field |
| $rename | Renames a field |
| $set | Sets a field's value |
| $unset | Removes a field from the document |
Using them
// Set likes to 2
db.posts.updateOne({ title: "Post Title 1" }, { $set: { likes: 2 } })
// Increment likes by 1
db.posts.updateMany({}, { $inc: { likes: 1 } })
// Rename the "likes" field to "stars"
db.posts.updateMany({}, { $rename: { likes: "stars" } })
// Remove the "category" field
db.posts.updateMany({}, { $unset: { category: "" } })
// Set lastUpdated to the current time
db.posts.updateMany({}, { $currentDate: { lastUpdated: true } })
$set vs $inc
$setreplaces a field's value with whatever you give it.$incadds a number to an existing numeric field. So{ $inc: { likes: 1 } }adds 1, while{ $set: { likes: 1 } }forces it to exactly 1.
TL;DR
$setassigns,$incincrements,$unsetremoves.$renamerenames a field;$currentDatestamps the current time.