0
0
MongoDBquery~5 mins

Computed pattern for pre-aggregation in MongoDB

Choose your learning style9 modes available
Introduction

Pre-aggregation helps speed up queries by calculating and storing results ahead of time.

When you want to quickly get totals or averages without recalculating every time.
When your data is large and running calculations on the fly is slow.
When you need to show summary reports that update regularly.
When you want to reduce the load on your database during busy times.
Syntax
MongoDB
db.collection.aggregate([
  {
    $group: {
      _id: <grouping_key>,
      <computed_field>: { $<aggregation_operator>: "$<field>" }
    }
  }
])

The $group stage groups documents by a key and computes values.

You can use operators like $sum, $avg, $max, and $min to compute fields.

Examples
Groups sales by product and sums the amount for each product.
MongoDB
db.sales.aggregate([
  {
    $group: {
      _id: "$product",
      totalSales: { $sum: "$amount" }
    }
  }
])
Calculates the average order total for each customer.
MongoDB
db.orders.aggregate([
  {
    $group: {
      _id: "$customerId",
      averageOrder: { $avg: "$total" }
    }
  }
])
Sample Program

This query groups orders by category, sums the quantity sold, and calculates the average price per category.

MongoDB
db.orders.aggregate([
  {
    $group: {
      _id: "$category",
      totalQuantity: { $sum: "$quantity" },
      averagePrice: { $avg: "$price" }
    }
  }
])
OutputSuccess
Important Notes

Pre-aggregation stores computed results to avoid repeating calculations.

Use indexes on grouping keys to improve aggregation speed.

Summary

Pre-aggregation calculates and stores summary data ahead of time.

Use $group with aggregation operators to compute values.

This pattern helps queries run faster on large data sets.