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

Aggregation Framework

Scorri per mostrare il 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?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 5. Capitolo 3

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 5. Capitolo 3
some-alt