Example Aggregation Pipeline
Let’s walk through an example using a collection of sales data. Suppose we have the following documents in a sales collection:
[
{ "item": "apple", "quantity": 10, "price": 1.0, "date": "2023-05-01" },
{ "item": "banana", "quantity": 5, "price": 0.5, "date": "2023-05-01" },
{ "item": "apple", "quantity": 7, "price": 1.0, "date": "2023-05-02" },
{ "item": "banana", "quantity": 10, "price": 0.5, "date": "2023-05-02" }
]
We want to calculate the total sales for each item.
Step 1: $match Stage
Filter documents to include only those with a quantity greater than 5:
{
$match: { quantity: { $gt: 5 } }
}
Step 2: $group Stage
Group the documents by the item field and calculate the total quantity and total sales:
{
$group: {
_id: "$item",
totalQuantity: { $sum: "$quantity" },
totalSales: { $sum: { $multiply: ["$quantity", "$price"] } }
}
}
Step 3: $sort Stage
Sort the results by totalSales in descending order:
{
$sort: { totalSales: -1 }
}
Step 4: $project Stage
Reshape the output documents to include only the fields item, totalQuantity, and totalSales:
{
$project: {
_id: 0,
item: "$_id",
totalQuantity: 1,
totalSales: 1
}
}
Explain the Concept of Aggregation Pipelines in MongoDB
The aggregation framework in MongoDB is a powerful feature that enables advanced data processing and analysis directly within the database. At the core of this framework is the aggregation pipeline, which allows you to transform and combine documents in a collection through a series of stages.
Table of Content
- Aggregation Pipelines
- Key Features of Aggregation Pipelines
- Common Aggregation Stages
- Example Aggregation Pipeline
- Complete Pipeline
- Conclusion
Contact Us