$set $unset $inc
$set assigns fields, $unset removes them and $inc adds to numbers atomically.
In this page:
Syntax
{ $set: { field: value } }
{ $unset: { field: "" } }
{ $inc: { field: number } }
$set $unset $inc
$set creates or overwrites fields (including nested paths), $unset deletes a field, and $inc increments or decrements a number, creating it if missing.
Multiple operators can appear in one update, each applied to different fields. $inc is safe under concurrency because it is atomic.
Note:
Use $inc for counters instead of read-modify-write in application code.
Example: $set $unset $inc
test> db.stats.insertOne({ _id: 1, name: "page", views: 10, draft: true, meta: { author: "Ada" } })
{ acknowledged: true, insertedId: 1 }
test> db.stats.updateOne({ _id: 1 }, { $inc: { views: 5 }, $unset: { draft: "" }, $set: { "meta.editor": "Bob" } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.stats.findOne()
{
_id: 1,
name: 'page',
views: 15,
meta: { author: 'Ada', editor: 'Bob' }
}
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using $set to increment a counter
- Combining two operators on the same field
- Forgetting $unset takes any value
Chapter Summary
- $set sets or overwrites
- $unset removes a field
- $inc adds a number atomically
- Operators combine on different fields
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: