Computed Pattern in MongoDB: What It Is and How to Use It
computed pattern in MongoDB refers to creating fields whose values are dynamically calculated from other fields within the same document, often using aggregation operators like $addFields or $project. This pattern helps generate new data on the fly without storing redundant information.How It Works
The computed pattern in MongoDB works by deriving new values from existing data inside documents. Imagine you have a recipe book and want to know the total calories for each recipe without writing it down separately. Instead, you calculate it whenever you look at the recipe. MongoDB does this by using aggregation stages like $addFields or $project to create new fields based on expressions.
This means you don’t store the computed value permanently but generate it when needed. It’s like having a calculator that adds numbers for you every time you ask, so your data stays clean and up-to-date without extra storage.
Example
This example shows how to compute a new field totalPrice by multiplying price and quantity fields in each document.
db.orders.aggregate([
{
$addFields: {
totalPrice: { $multiply: ["$price", "$quantity"] }
}
}
])When to Use
Use the computed pattern when you want to avoid storing repeated or derived data that can be calculated from existing fields. It is helpful for:
- Calculating totals, averages, or other summaries on the fly.
- Generating dynamic fields for reports or views without changing the original data.
- Keeping your database storage efficient and consistent by not duplicating data.
For example, an e-commerce app can compute order totals or discounts dynamically instead of storing them, ensuring accuracy if prices or quantities change.
Key Points
- The computed pattern creates fields dynamically during queries or aggregations.
- It uses MongoDB aggregation operators like
$addFieldsand$project. - Helps keep data storage efficient by avoiding redundant fields.
- Useful for calculations like totals, averages, or conditional values.