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

$set $unset $inc का उपयोग

$set fields assign करता है, $unset इन्हें remove करता है, और $inc atomically numbers में add करता है।

In this page:

  1. $set $unset $inc
Syntax
javascript
{ $set: { field: value } }
{ $unset: { field: "" } }
{ $inc: { field: number } }

$set $unset $inc

$set fields बनाता या overwrite करता है (nested paths समेत), $unset एक field delete करता है, और $inc एक number increment या decrement करता है, missing होने पर इसे बनाते हुए।

एक update में कई operators appear हो सकते हैं, हर एक अलग fields पर apply होते हुए। $inc concurrency के अंतर्गत safe है क्योंकि यह atomic है।

Note: application code में read-modify-write की बजाय counters के लिए $inc इस्तेमाल करें।

उदाहरण: $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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक counter increment करने के लिए $set इस्तेमाल करना
  2. same field पर दो operators combine करना
  3. यह भूल जाना कि $unset कोई भी value लेता है
चैप्टर सारांश
  • $set set या overwrite करता है
  • $unset एक field remove करता है
  • $inc atomically एक number add करता है
  • Operators अलग fields पर combine होते हैं
🔒

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.