← Back to MongoDB Course | Chapter 6: Query Operators | Lesson 4 of 7

Array Operators ($all $elemMatch $size) की जानकारी

Array operators array fields के contents और size query करते हैं।
Syntax
javascript
{ array_field: { $all: [value1, value2] } }
{ array_field: { $elemMatch: { key: value } } }
{ array_field: { $size: n } }

Array Operators ($all $elemMatch $size)

एक array field में एक value match करना plain equality से काम करता है। $all को कई values present होने की ज़रूरत है, $size एक exact length match करता है, और $elemMatch को एक element से एक साथ कई conditions satisfy होने की ज़रूरत है।

$elemMatch के बिना, conditions अलग elements से satisfy हो सकती हैं।

Note: जब same array element के लिए कई conditions hold होनी चाहिए $elemMatch इस्तेमाल करें।

उदाहरण: Array operators ($all $elemMatch $size)

bash
test> db.posts.insertMany([
...   { _id: 1, tags: ["js", "node", "db"], scores: [{ who: "a", v: 5 }, { who: "b", v: 9 }] },
...   { _id: 2, tags: ["js"], scores: [{ who: "a", v: 9 }, { who: "b", v: 1 }] }
... ])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.posts.find({ tags: "node" }, { _id: 1 })
[ { _id: 1 } ]
test> db.posts.find({ tags: { $all: ["js", "db"] } }, { _id: 1 })
[ { _id: 1 } ]
test> db.posts.find({ tags: { $size: 1 } }, { _id: 1 })
[ { _id: 2 } ]
test> db.posts.find({ scores: { $elemMatch: { who: "b", v: { $gt: 5 } } } }, { _id: 1 })
[ { _id: 1 } ]

⚠️ 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. यह उम्मीद करना कि separate conditions एक element से bind होंगी
  2. ranges के साथ $size इस्तेमाल करना
  3. यह भूल जाना कि subdocuments के arrays को dotted paths चाहिए
चैप्टर सारांश
  • Equality किसी भी element से match करती है
  • $all को listed हर value चाहिए
  • $size exact length match करता है
  • $elemMatch conditions को एक element से bind करता है
🔒

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.