← Back to MongoDB Course | Chapter 4: CRUD — Update | Lesson 3 of 7

$set $unset $inc

$set assigns fields, $unset removes them and $inc adds to numbers atomically.

In this page:

  1. $set $unset $inc
Syntax
javascript
{ $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

bash
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
  1. Using $set to increment a counter
  2. Combining two operators on the same field
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.