In this lesson, you will learn how to optimize read-heavy applications by embedding pre-calculated aggregates directly into your documents to avoid expensive runtime calculations.
Why Calculate on the Fly?
In many applications, we frequently display the same summary data—such as the total number of comments on a blog post or the average rating of a product. If you calculate these values using an aggregation pipeline every time a user loads a page, you consume significant CPU and memory resources. As your data scales, these "on-the-fly" calculations become a bottleneck for read performance.
The Computed Pattern
The Computed Pattern moves the computational burden from the read operation to the write operation. Instead of querying the database to sum up values, you store the result as a field within your document. When related data changes (e.g., a new comment is added), you update both the document and the stored aggregate value in a single atomic operation.
Imagine a products collection where we track reviews. Instead of aggregating all reviews every time a customer views the page, we store an averageRating field:
{
"_id": "laptop_001",
"name": "Pro Laptop",
"averageRating": 4.7,
"reviewCount": 154
}
When a user submits a new 5-star review, your application code updates the document like this:
db.products.updateOne(
{ _id: "laptop_001" },
{
$set: { averageRating: 4.72 },
$inc: { reviewCount: 1 }
}
);
Strategic Trade-offs
This pattern trades a small amount of extra work during the write process for a massive gain in read speed. Because the value is already present in the document, your read queries become simple lookups, which are highly efficient and easy to index.
While this adds slight complexity to your application logic (you must ensure the computed value is kept in sync with the source data), it is an essential strategy for high-traffic systems where the cost of re-calculating data exceeds the cost of maintaining a pre-computed field.
Key Takeaway: The Computed Pattern eliminates expensive runtime aggregations by storing pre-calculated values directly in the document, shifting the computational cost from read-time to write-time.