MongoDB / Aggregation in MongoDB
Basic Aggregation
This tutorial will introduce you to the basic concepts of MongoDB aggregation. You'll learn how to use different stages of the aggregation pipeline to transform your documents.
Section overview
4 resourcesCovers the aggregation framework in MongoDB for processing and transforming data.
1. Introduction
- Goal: This tutorial aims to introduce you to the basic concepts of MongoDB aggregation. Aggregation operations process data records and return computed results. Aggregation in MongoDB is handled via the aggregation pipeline.
- Learning Outcome: By the end of this tutorial, you will understand the basic concepts of MongoDB aggregation and how to use different stages of the aggregation pipeline to transform your documents.
- Prerequisites: Basic knowledge of MongoDB and JavaScript is required. Familiarity with MongoDB's query language would also be beneficial.
2. Step-by-Step Guide
2.1 Aggregation Pipeline
The aggregation pipeline is a framework for data aggregation modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms the documents into an aggregated result. Each stage of the pipeline processes the documents as they pass along from one stage to another.
2.2 Pipeline Operators
Pipeline operators provide tools to perform operations like sorting, grouping, and calculating aggregate values. Here are some common operators:
$match- Filters the documents to pass only documents that match the specified condition(s) to the next pipeline stage.$group- Groups input documents by a specified identifier expression and applies the accumulator expression(s), if specified, to each group.$sum- Calculates and returns the sum of numeric values.$sumcan be used in$groupstage.$sort- Reorders the document stream by a specified sort key. Only the order changes; the documents remain unmodified.
3. Code Examples
3.1 Using $match and $group
// Consider a collection with the following documents
[
{ "_id": 1, "item": "apple", "price": 1, "quantity": 5 },
{ "_id": 2, "item": "banana", "price": 1.5, "quantity": 5 },
{ "_id": 3, "item": "apple", "price": 1, "quantity": 10 },
{ "_id": 4, "item": "banana", "price": 1.5, "quantity": 7 }
]
// Aggregation query
db.collection.aggregate([
{ $match: { item: "apple" } },
{
$group: {
_id: "$item",
total: { $sum: { $multiply: [ "$price", "$quantity" ] } }
}
}
])
// Here, $match filters out only documents where item is 'apple'.
// Then, $group groups these filtered documents by 'item' and calculates the total cost.
Expected Result:
[
{ "_id": "apple", "total": 15 }
]
4. Summary
You have learned the basic concepts of MongoDB aggregation and how to use different stages of the aggregation pipeline. Continue practicing these concepts and try out different aggregation operations.
5. Practice Exercises
- Given a collection of students with fields "name", "age", and "grade", write an aggregation query to find the average grade of students over the age of 15.
- Given a collection of products with fields "product_name", "price", and "quantity", write an aggregation query to find the total value of each product (price * quantity).
Solutions:
db.students.aggregate([
{ $match: { age: { $gt: 15 } } },
{ $group: { _id: "$name", avgGrade: { $avg: "$grade" } } }
])
Here, we first filter students over the age of 15. Then, we group by name and calculate the average grade.
db.products.aggregate([
{ $group: { _id: "$product_name", totalValue: { $sum: { $multiply: ["$price", "$quantity"] } } } }
])
We group by product_name and calculate the total value of each product by multiplying price and quantity, then summing them up.
Keep practicing with different operators and complex queries to become proficient in MongoDB aggregation.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article