$group का उपयोग
$group documents को एक key से groups में collect करता है और हर group के लिए totals, averages, और बाकी compute करता है।
In this page:
Syntax
{ $group: {
_id: "$field",
total: { $sum: "$amount" },
average: { $avg: "$amount" }
} }
$group
$group stage का _id field grouping key define करता है, और बाकी fields $sum, $avg, $min, $max, $push, और $addToSet जैसे accumulators hold करती हैं।
सब कुछ एक result में aggregate करने के लिए _id: null इस्तेमाल करें। Group output का order guaranteed नहीं है, इसलिए $sort add करें।
Note:
$group output unordered है; इसके बाद $sort करें।
उदाहरण: $group
test> db.sales.insertMany([
... { _id: 1, item: "pen", qty: 5 }, { _id: 2, item: "book", qty: 1 },
... { _id: 3, item: "pen", qty: 10 }, { _id: 4, item: "book", qty: 3 }, { _id: 5, item: "lamp", qty: 2 }
... ])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
}
test> db.sales.aggregate([{ $group: { _id: "$item", totalQty: { $sum: "$qty" }, orders: { $sum: 1 } } }, { $sort: { _id: 1 } }])
[
{ _id: 'book', totalQty: 4, orders: 2 },
{ _id: 'lamp', totalQty: 2, orders: 1 },
{ _id: 'pen', totalQty: 15, orders: 2 }
]
test> db.sales.aggregate([{ $group: { _id: null, avgQty: { $avg: "$qty" }, maxQty: { $max: "$qty" } } }])
[ { _id: null, avgQty: 4.2, maxQty: 10 } ]
⚠️ 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. #}
आम गलतियां
- _id key भूल जाना
- sorted output की उम्मीद करना
- $sum: 1 बनाम $sum: "$field" गलत तरीके से इस्तेमाल करना
चैप्टर सारांश
- _id group key है
- Accumulators: $sum $avg $min $max $push उपलब्ध हैं
- _id null सब कुछ group करता है
- Output unordered है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: