Introduction
Pre-aggregation helps speed up queries by calculating and storing results ahead of time.
Pre-aggregation helps speed up queries by calculating and storing results ahead of time.
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.
db.sales.aggregate([
{
$group: {
_id: "$product",
totalSales: { $sum: "$amount" }
}
}
])db.orders.aggregate([
{
$group: {
_id: "$customerId",
averageOrder: { $avg: "$total" }
}
}
])This query groups orders by category, sums the quantity sold, and calculates the average price per category.
db.orders.aggregate([
{
$group: {
_id: "$category",
totalQuantity: { $sum: "$quantity" },
averagePrice: { $avg: "$price" }
}
}
])Pre-aggregation stores computed results to avoid repeating calculations.
Use indexes on grouping keys to improve aggregation speed.
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.
[{ $group: { _id: "$category", total: { $sum: "$amount" } } }]
Assuming the collection has documents: {category: "A", amount: 10}, {category: "B", amount: 5}, {category: "A", amount: 15}.[{ $group: { _id: "$category", total: { $sum: "amount" } } }]Pass the test and this pattern moves unknown