MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Aggregation Pipeline Architecture: $match, $group, $project & $sort0%
Study Materials
MongoDB & MongooseProgress 0%
1.1Document Databases vs Relational SQL: CAP Theorem & When to Use NoSQL1.2JSON vs BSON Data Types & MongoDB Internal Storage Engine (WiredTiger)1.3MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUI
4.1One-to-Few (Embedded) vs One-to-Many (Referenced) Data Modeling4.2Query Population with .populate() & Multi-Level Population4.3Aggregation Pipeline Architecture: $match, $group, $project & $sort4.4Multi-Table Joins with $lookup & Array Flattening with $unwind4.5Database Indexing Strategies (Single, Compound, TTL) & Query Optimization
HomeTutorialsMongoDB & MongooseAggregation Pipeline Architecture: $match, $group, $project & $sort
Multi-Table Joins with $lookup & Array Flattening with $unwind

Aggregation Pipeline Architecture: $match, $group, $project & $sort

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While .find() is ideal for simple document retrieval, complex data analytics, reports, metric calculations, and data transformations require the MongoDB Aggregation Pipeline. Documents pass through a multi-stage pipeline where each stage transforms the data stream sequentially.


1. The Pipeline Concept

Think of the aggregation pipeline as an industrial assembly line:

1Raw Collection ---> [$match] ---> [$project] ---> [$group] ---> [$sort] ---> Final Report

The output of each stage serves as the input to the next stage.


2. The Core Pipeline Stages

  • $match: Filters documents (analogous to SQL WHERE). Place this as early as possible in the pipeline to utilize indexes and reduce data volume for subsequent stages!
  • $project: Reshapes documents: adds computed fields, renames fields, or excludes existing fields (analogous to SQL SELECT).
  • $group: Groups documents by a specified identifier key and performs accumulative calculations like sum, average, min, max (analogous to SQL GROUP BY).
  • $sort: Sorts the resulting stream of documents (analogous to SQL ORDER BY).

3. Real-World Aggregation: Course Revenue & Rating Analytics

Calculate statistics for all published courses grouped by category:

1const categoryStats = await Course.aggregate([
2 // Stage 1: Filter only published courses
3 {
4 $match: { isPublished: true, rating: { $gte: 4.0 } }
5 },
6
7 // Stage 2: Group by category and compute aggregate metrics
8 {
9 $group: {
10 _id: '$category', // Grouping key ($ prefix denotes field reference)
11 totalCourses: { $sum: 1 }, // Count documents
12 avgPrice: { $avg: '$price' },
13 minPrice: { $min: '$price' },
14 maxPrice: { $max: '$price' },
15 totalEnrollments: { $sum: '$enrollmentCount' }
16 }
17 },
18 
19 // Stage 3: Reshape output and round decimals
20 {
21 $project: {
22 category: '$_id',
23 _id: 0, // Exclude raw _id
24 totalCourses: 1,
25 totalEnrollments: 1,
26 avgPrice: { $round: ['$avgPrice', 2] },
27 priceRange: {
28 $concat: ['$', { $toString: '$minPrice' }, ' - $', { $toString: '$maxPrice' }]
29 }
30 }
31 },
32 
33 // Stage 4: Sort by total revenue/enrollments descending
34 {
35 $sort: { totalEnrollments: -1 }
36 }
37]);
38 
39console.log(categoryStats);

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
In MongoDB Aggregation, what does the $match stage do?
Question 2
Why is placing the $match stage at the very beginning of an aggregation pipeline considered a best practice?
Question 3
In the $group stage, how do you reference the value of an existing document field named category?
Question 4
Which accumulator operator computes the total count of documents inside a $group stage?
Question 5
What does setting _id: 0 in a $project stage accomplish?

Next Lesson

Multi-Table Joins with $lookup & Array Flattening with $unwind

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Query Population with .populate() & Multi-Level PopulationMulti-Table Joins with $lookup & Array Flattening with $unwind

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master MongoDB & Mongoose with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext