$unwind का उपयोग
$unwind एक array field split करता है ताकि हर element इसका अपना document बन जाए।
In this page:
Syntax
{ $unwind: "$array_field" }
$unwind
array [a, b, c] वाले एक document के लिए, $unwind तीन documents output करता है, हर एक में उस field में एक element। Empty या missing arrays वाले documents drop हो जाते हैं जब तक preserveNullAndEmptyArrays true न हो।
यह अक्सर elements count या total करने के लिए $group के साथ pair होता है।
Note:
Empty arrays वाले documents रखने के लिए preserveNullAndEmptyArrays इस्तेमाल करें।
उदाहरण: $unwind
test> db.posts.insertMany([{ _id: 1, title: "A", tags: ["js", "db"] }, { _id: 2, title: "B", tags: ["js"] }, { _id: 3, title: "C", tags: [] }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.posts.aggregate([{ $unwind: "$tags" }, { $project: { _id: 0, title: 1, tags: 1 } }])
[
{ title: 'A', tags: 'js' },
{ title: 'A', tags: 'db' },
{ title: 'B', tags: 'js' }
]
test> db.posts.aggregate([{ $unwind: "$tags" }, { $group: { _id: "$tags", posts: { $sum: 1 } } }, { $sort: { _id: 1 } }])
[ { _id: 'db', posts: 1 }, { _id: 'js', posts: 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. #}
आम गलतियां
- यह उम्मीद करना कि empty arrays रखी जाएँगी
- path में $ भूल जाना
- यह भूल जाना कि unwinding documents multiply करता है
चैप्टर सारांश
- $unwind प्रति element एक document emit करता है
- Empty arrays document drop करती हैं
- preserveNullAndEmptyArrays इन्हें रखता है
- $group के साथ अच्छी तरह pair होता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: