Complete Pipeline
Combining these stages into a complete pipeline:
db.sales.aggregate([
{ $match: { quantity: { $gt: 5 } } },
{ $group: { _id: "$item", totalQuantity: { $sum: "$quantity" }, totalSales: { $sum: { $multiply: ["$quantity", "$price"] } } } },
{ $sort: { totalSales: -1 } },
{ $project: { _id: 0, item: "$_id", totalQuantity: 1, totalSales: 1 } }
])
Output: The result of running this pipeline might be:
[
{ "item": "banana", "totalQuantity": 15, "totalSales": 7.5 },
{ "item": "apple", "totalQuantity": 17, "totalSales": 17.0 }
]
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