SlideShare a Scribd company logo
Joe Nyirenda
MongoDB Aggregations in
10 Minutes
A Quick Guide to Mastering MongoDB’s Aggregation Framework
Agenda
Introduction to Aggregations
Aggregation Pipeline
Common Stages in Aggregation
Example Queries
Use Cases for Aggregations
Conclusion
Introduction to MongoDB Aggregations
What are Aggregations?
A way to process data and return
computed results.
Similar to SQL’s GROUP BY or SUM but
more powerful.
Why use Aggregations?
Useful for data analysis, reporting, and
transforming documents.
Aggregation Pipeline Overview
Aggregation Pipeline:
A multi-stage pipeline that transforms
documents.
Each stage performs an operation and
passes results to the next stage.
Structure:
[{ stage1 }, { stage2 }, ... { stageN }]
Stages are executed sequentially.
Discrete
Processing Stages
● Stages can be streaming or
blocking; favour the usage of
streaming stages
● The order of stages matters, apply
best practices
● Stages are easier to debug and
maintain
Common Aggregation Stages
Key Aggregation
Stages:
1. $match – Filters
documents based on
conditions.
2. $group – Groups
documents by a field
and applies aggregate
functions.
3. $sort – Sorts
documents by a field.
4. $project – Reshapes
documents,
including/excluding
fields.
5. $limit – Limits the
number of documents
returned.
Stage Example 1: $match and $group
$match and $group Example:
db.sales.aggregate([
{ $match: { status: 'completed' } },
{ $group: { _id: '$product', total: { $sum: '$amount' } } }
])
Explanation:
Filters documents where status is 'completed'.
Groups by product and sums up the amount.
Stage Example 2: $project and $sort
$project and $sort Example:
db.sales.aggregate([
{ $project: { product: 1, amount: 1, profit: { $subtract: ['$revenue', '$cost'] } } },
{ $sort: { profit: -1 } }
])
Explanation:
Projects product, amount, and calculates profit.
Sorts documents by profit in descending order.
Real-World Use Case: Monthly Sales Report
Problem:
Generate a monthly sales report showing total sales and average sale amount for each category.
Solution:
db.sales.aggregate([
{ $match: { date: { $gte: new ISODate('2023-01-01'), $lt: new ISODate('2023-02-01') } } },
{ $group: { _id: '$category', totalSales: { $sum: '$amount' }, avgSale: { $avg: '$amount' } } }
])
Explanation:
Filters sales for January 2023.
Groups by category and calculates total and average sales.
Aggregation Performance Tips
Performance Tips: Use indexes
effectively with $match
and $sort.
Minimize the number
of documents passed
between stages.
Use $limit early in the
pipeline to reduce
processing time.
Conclusion and Further Learning
Conclusion
Aggregations in MongoDB provide powerful data transformation tools.
Pipelines combine multiple stages for complex queries.
Practice with real datasets to master these concepts.
Further Reading:
MongoDB Documentation on Aggregations
MongoDB University Courses

More Related Content

PPTX
Aggregation Presentation for databses (1).pptx
PPTX
SH 2 - SES 3 - MongoDB Aggregation Framework.pptx
PDF
Experiment no 05
ODP
Aggregation Framework in MongoDB Overview Part-1
PPTX
The Aggregation Framework
PDF
MongoDB Aggregation Framework
PPTX
Aggregation in MongoDB
PDF
Aggregation Framework MongoDB Days Munich
Aggregation Presentation for databses (1).pptx
SH 2 - SES 3 - MongoDB Aggregation Framework.pptx
Experiment no 05
Aggregation Framework in MongoDB Overview Part-1
The Aggregation Framework
MongoDB Aggregation Framework
Aggregation in MongoDB
Aggregation Framework MongoDB Days Munich

Similar to Learning MongoDB Aggregations in 10 Minutes (20)

PPTX
MongoDB Aggregation MongoSF May 2011
PDF
Mongo db aggregation guide
PDF
Mongo db aggregation-guide
PPTX
Introduction to MongoDB
PDF
All about aggregations
PPTX
How to learn MongoDB for beginner's
PPTX
MongoDB's New Aggregation framework
PPTX
How to leverage MongoDB for Big Data Analysis and Operations with MongoDB's A...
PPTX
MongoDB Evenings Toronto - Monolithic to Microservices with MongoDB
PPTX
Webinar: Applikationsentwicklung mit MongoDB : Teil 5: Reporting & Aggregation
PDF
Webinar: Managing Real Time Risk Analytics with MongoDB
PPTX
mongodb-aggregation-may-2012
PDF
MongoDB 4.0 새로운 기능 소개
PPTX
1403 app dev series - session 5 - analytics
PDF
2016 feb-23 pyugre-py_mongo
PDF
Using MongoDB and Python
PDF
MongoDB Meetup
PPTX
MongoDB_ppt.pptx
PPTX
Joins and Other Aggregation Enhancements Coming in MongoDB 3.2
PDF
Querying Mongo Without Programming Using Funql
MongoDB Aggregation MongoSF May 2011
Mongo db aggregation guide
Mongo db aggregation-guide
Introduction to MongoDB
All about aggregations
How to learn MongoDB for beginner's
MongoDB's New Aggregation framework
How to leverage MongoDB for Big Data Analysis and Operations with MongoDB's A...
MongoDB Evenings Toronto - Monolithic to Microservices with MongoDB
Webinar: Applikationsentwicklung mit MongoDB : Teil 5: Reporting & Aggregation
Webinar: Managing Real Time Risk Analytics with MongoDB
mongodb-aggregation-may-2012
MongoDB 4.0 새로운 기능 소개
1403 app dev series - session 5 - analytics
2016 feb-23 pyugre-py_mongo
Using MongoDB and Python
MongoDB Meetup
MongoDB_ppt.pptx
Joins and Other Aggregation Enhancements Coming in MongoDB 3.2
Querying Mongo Without Programming Using Funql
Ad

More from techprane (17)

PDF
REDIS + FastAPI: Implementing a Rate Limiter
PDF
Performance Optimization MongoDB: Compound Indexes
PPTX
SSO with Social Login Integration & FastAPI Simplified
PDF
A Beginner's Guide to Tortoise ORM and PostgreSQL
PDF
Boost Your API with Asynchronous Programming in FastAPI
PDF
Top 10 Network Troubleshooting Commands.pdf
PPTX
Using jq to Process and Query MongoDB Logs
PPTX
How to Integrate PostgreSQL with Prometheus
PPTX
10 Basic Git Commands to Get You Started
PPTX
Top Linux 10 Commands for Windows Admins
PPTX
Implementing full text search with Apache Solr
PPTX
How to Overcome Doubts as a New Developer(Imposter Syndrome)
PPTX
How to Use JSONB in PostgreSQL for Product Attributes Storage
PDF
A Beginners Guide to Building MicroServices with FastAPI
PDF
Implementing Schema Validation in MongoDB with Pydantic
PPTX
Storing Large Image Files in MongoDB Using GRIDFS
PPTX
Open Source Mapping with Python, and MongoDB
REDIS + FastAPI: Implementing a Rate Limiter
Performance Optimization MongoDB: Compound Indexes
SSO with Social Login Integration & FastAPI Simplified
A Beginner's Guide to Tortoise ORM and PostgreSQL
Boost Your API with Asynchronous Programming in FastAPI
Top 10 Network Troubleshooting Commands.pdf
Using jq to Process and Query MongoDB Logs
How to Integrate PostgreSQL with Prometheus
10 Basic Git Commands to Get You Started
Top Linux 10 Commands for Windows Admins
Implementing full text search with Apache Solr
How to Overcome Doubts as a New Developer(Imposter Syndrome)
How to Use JSONB in PostgreSQL for Product Attributes Storage
A Beginners Guide to Building MicroServices with FastAPI
Implementing Schema Validation in MongoDB with Pydantic
Storing Large Image Files in MongoDB Using GRIDFS
Open Source Mapping with Python, and MongoDB
Ad

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Modernizing your data center with Dell and AMD
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
cuic standard and advanced reporting.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Machine learning based COVID-19 study performance prediction
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Cloud computing and distributed systems.
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
Teaching material agriculture food technology
Encapsulation_ Review paper, used for researhc scholars
Modernizing your data center with Dell and AMD
Mobile App Security Testing_ A Comprehensive Guide.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
cuic standard and advanced reporting.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
The Rise and Fall of 3GPP – Time for a Sabbatical?
Machine learning based COVID-19 study performance prediction
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Approach and Philosophy of On baking technology
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Diabetes mellitus diagnosis method based random forest with bat algorithm
Spectral efficient network and resource selection model in 5G networks
Cloud computing and distributed systems.
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Teaching material agriculture food technology

Learning MongoDB Aggregations in 10 Minutes

  • 1. Joe Nyirenda MongoDB Aggregations in 10 Minutes A Quick Guide to Mastering MongoDB’s Aggregation Framework
  • 2. Agenda Introduction to Aggregations Aggregation Pipeline Common Stages in Aggregation Example Queries Use Cases for Aggregations Conclusion
  • 3. Introduction to MongoDB Aggregations What are Aggregations? A way to process data and return computed results. Similar to SQL’s GROUP BY or SUM but more powerful. Why use Aggregations? Useful for data analysis, reporting, and transforming documents.
  • 4. Aggregation Pipeline Overview Aggregation Pipeline: A multi-stage pipeline that transforms documents. Each stage performs an operation and passes results to the next stage. Structure: [{ stage1 }, { stage2 }, ... { stageN }] Stages are executed sequentially.
  • 5. Discrete Processing Stages ● Stages can be streaming or blocking; favour the usage of streaming stages ● The order of stages matters, apply best practices ● Stages are easier to debug and maintain
  • 6. Common Aggregation Stages Key Aggregation Stages: 1. $match – Filters documents based on conditions. 2. $group – Groups documents by a field and applies aggregate functions. 3. $sort – Sorts documents by a field. 4. $project – Reshapes documents, including/excluding fields. 5. $limit – Limits the number of documents returned.
  • 7. Stage Example 1: $match and $group $match and $group Example: db.sales.aggregate([ { $match: { status: 'completed' } }, { $group: { _id: '$product', total: { $sum: '$amount' } } } ]) Explanation: Filters documents where status is 'completed'. Groups by product and sums up the amount.
  • 8. Stage Example 2: $project and $sort $project and $sort Example: db.sales.aggregate([ { $project: { product: 1, amount: 1, profit: { $subtract: ['$revenue', '$cost'] } } }, { $sort: { profit: -1 } } ]) Explanation: Projects product, amount, and calculates profit. Sorts documents by profit in descending order.
  • 9. Real-World Use Case: Monthly Sales Report Problem: Generate a monthly sales report showing total sales and average sale amount for each category. Solution: db.sales.aggregate([ { $match: { date: { $gte: new ISODate('2023-01-01'), $lt: new ISODate('2023-02-01') } } }, { $group: { _id: '$category', totalSales: { $sum: '$amount' }, avgSale: { $avg: '$amount' } } } ]) Explanation: Filters sales for January 2023. Groups by category and calculates total and average sales.
  • 10. Aggregation Performance Tips Performance Tips: Use indexes effectively with $match and $sort. Minimize the number of documents passed between stages. Use $limit early in the pipeline to reduce processing time.
  • 11. Conclusion and Further Learning Conclusion Aggregations in MongoDB provide powerful data transformation tools. Pipelines combine multiple stages for complex queries. Practice with real datasets to master these concepts. Further Reading: MongoDB Documentation on Aggregations MongoDB University Courses