Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Aggregation Framework | Querying and Aggregation
MongoDB and Mongoose Essentials

Aggregation Framework

Deslize para mostrar o menu

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:

  • $match filters documents to only include those with an amount greater than 100;
  • $group organizes the filtered documents by category and calculates the sum of amount for each group;
  • $project shapes the output to include only the category and totalSales fields.

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.

question mark

Which of the following statements about the aggregation pipeline stages in the provided code example is correct?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 5. Capítulo 3

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 5. Capítulo 3
some-alt