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

Aggregation Framework

メニューを表示するにはスワイプしてください

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?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 5.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 5.  3
some-alt