← Back to MongoDB Course | Chapter 7: Aggregation | Lesson 3 of 7

$group का उपयोग

$group documents को एक key से groups में collect करता है और हर group के लिए totals, averages, और बाकी compute करता है।

In this page:

  1. $group
Syntax
javascript
{ $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

bash
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. #}
आम गलतियां
  1. _id key भूल जाना
  2. sorted output की उम्मीद करना
  3. $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:

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.