Upsert क्या है
एक upsert एक matching document update करता है या अगर कुछ match न हो एक नया insert करता है।
In this page:
Syntax
db.collection_name.updateOne(
filter,
{ $set: { field: value } },
{ upsert: true }
)
Upsert
एक update में { upsert: true } add करें। अगर filter कुछ भी match न करे, MongoDB filter के equality fields plus update से एक document बनाता है। $setOnInsert सिर्फ तभी fields set करता है जब एक नया document बने।
Concurrency में पूरी तरह safe होने के लिए Upserts को एक unique index चाहिए।
Note:
createdAt जैसे fields के लिए $setOnInsert इस्तेमाल करें जो कभी नहीं बदलने चाहिए।
उदाहरण: Upsert
test> db.visits.updateOne({ _id: "home" }, { $inc: { count: 1 } }, { upsert: true })
{
acknowledged: true,
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 1,
upsertedId: 'home'
}
test> db.visits.updateOne({ _id: "home" }, { $inc: { count: 1 } }, { upsert: true })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.visits.find()
[ { _id: 'home', count: 2 } ]
⚠️ 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. #}
आम गलतियां
- बिना एक unique index के upsert करना
- यह उम्मीद करना कि एक upsert हमेशा insert करेगा
- Operators वाले Filters unexpected fields produce करते हुए
चैप्टर सारांश
- upsert: true update या insert करता है
- Filter equality fields नया document seed करते हैं
- $setOnInsert सिर्फ insert पर set करता है
- safety के लिए एक unique index इस्तेमाल करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: