Aggregation Framework
Svep för att visa menyn
To analyze and transform data in powerful ways, you can use MongoDB's aggregation framework. This framework enables you to process documents through a sequence of stages, forming an aggregation pipeline. Each stage transforms the data as it passes through, allowing you to filter, group, and reshape your results for reporting and analytics.
Consider the following aggregation pipeline, where you want to analyze sales data to find the total sales for each product category, but only for sales above $100:
db.sales.aggregate([
// Filter documents where sale amount is greater than 100
{ $match: { amount: { $gt: 100 } } },
// Group documents by category and calculate total sales per category
{
$group: {
_id: "$category",
totalSales: { $sum: "$amount" }
}
},
// Project the output to include category and totalSales fields
{
$project: {
_id: 0,
category: "$_id",
totalSales: 1
}
}
]);
In this example, the pipeline uses three stages:
$matchfilters documents to only include those with anamountgreater than 100;$grouporganizes the filtered documents bycategoryand calculates the sum ofamountfor each group;$projectshapes the output to include only thecategoryandtotalSalesfields.
The aggregation pipeline is a flexible tool for data analysis. You can chain multiple stages together to handle complex reporting needs. The order of stages matters, as each stage operates on the output from the previous one. For example, you might first filter data with $match, then summarize it with $group, and finally format your results with $project. This approach allows you to build custom analytics and reports directly within the database, making MongoDB a strong choice for applications that require advanced data processing.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal