Arrays के साथ काम करना
Arrays powerful हैं लेकिन care चाहिए: इनका size bound करें और जो fields आप search करते हैं उन्हें index करें।
In this page:
Syntax
db.collection_name.updateOne(
filter,
{ $push: { array_field: { $each: [value], $slice: -n } } }
)
Arrays के साथ काम करना
एक fixed-size array रखने के लिए $slice के साथ $push इस्तेमाल करें, unique values के लिए $addToSet, और elements update करने के लिए $ और $[] जैसे positional operators।
Multikey indexes array fields cover करते हैं। बिना limit बढ़ने वाले arrays से बचें क्योंकि documents 16 MB पर capped हैं।
Note:
$each और $slice के साथ $push सिर्फ सबसे recent N items रखता है।
उदाहरण: Working with arrays
test> db.feeds.insertOne({ _id: 1, recent: [] })
{ acknowledged: true, insertedId: 1 }
test> for (const n of [1, 2, 3, 4, 5]) db.feeds.updateOne({ _id: 1 }, { $push: { recent: { $each: ["post" + n], $slice: -3 } } })
test> db.feeds.findOne()
{ _id: 1, recent: [ 'post3', 'post4', 'post5' ] }
test> db.carts.insertOne({ _id: 1, items: [{ sku: "A", qty: 1 }, { sku: "B", qty: 2 }] })
{ acknowledged: true, insertedId: 1 }
test> db.carts.updateOne({ _id: 1 }, { $set: { "items.1.qty": 5 } }) // by position; the positional $ operator targets the matched element in real MongoDB
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.carts.findOne()
{ _id: 1, items: [ { sku: 'A', qty: 1 }, { sku: 'B', qty: 5 } ] }
⚠️ 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. #}
आम गलतियां
- Arrays को unbounded छोड़ना
- पूरी field फिर से लिखकर arrays update करना
- Array position operators ignore करना
चैप्टर सारांश
- $slice arrays bounded रखता है
- $addToSet values unique रखता है
- Positional operators elements update करते हैं
- Multikey indexes arrays cover करते हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: