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

Aggregation Pipeline का परिचय

एक aggregation pipeline documents को stages की एक series से गुज़ारता है, हर एक data transform करते हुए।

In this page:

  1. Aggregation Pipeline
Syntax
javascript
db.collection_name.aggregate([
  { $match: filter },
  { $group: { _id: "$field", total: { $sum: 1 } } },
  { $sort: { total: -1 } }
])

Aggregation Pipeline

db.collection.aggregate([stage1, stage2, ...]) documents को $match, $group, $project, और $sort जैसे stages से भेजता है। हर stage का output अगले को feed होता है।

$match को जल्दी रखना हर बाद की stage को process करना पड़ने वाला data कम करता है और indexes को मदद करने देता है।

Note: जितना जल्दी हो सके $match से filter करें।

उदाहरण: Aggregation pipeline

bash
test> db.sales.insertMany([
...   { _id: 1, item: "pen", qty: 5, price: 2 }, { _id: 2, item: "book", qty: 1, price: 12 },
...   { _id: 3, item: "pen", qty: 10, price: 2 }, { _id: 4, item: "lamp", qty: 2, price: 30 }
... ])
{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.sales.aggregate([
...   { $match: { qty: { $gte: 2 } } },
...   { $project: { _id: 0, item: 1, total: { $multiply: ["$qty", "$price"] } } },
...   { $sort: { total: -1 } }
... ])
[
  { item: 'lamp', total: 60 },
  { item: 'pen', total: 20 },
  { item: 'pen', total: 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. एक array की बजाय stages को separate arguments की तरह pass करना
  2. एक expensive $group के बाद $match रखना
  3. यह भूल जाना कि हर stage एक separate object है
चैप्टर सारांश
  • aggregate stages का एक array लेता है
  • हर stage अगले को feed करता है
  • $match जल्दी करें
  • Stages एक operator वाले objects हैं
🔒

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.