0
0
MongodbConceptBeginner · 3 min read

Computed Pattern in MongoDB: What It Is and How to Use It

The 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.

mongodb
db.orders.aggregate([
  {
    $addFields: {
      totalPrice: { $multiply: ["$price", "$quantity"] }
    }
  }
])
Output
[ { "_id": 1, "price": 10, "quantity": 2, "totalPrice": 20 }, { "_id": 2, "price": 5, "quantity": 4, "totalPrice": 20 } ]
🎯

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 $addFields and $project.
  • Helps keep data storage efficient by avoiding redundant fields.
  • Useful for calculations like totals, averages, or conditional values.

Key Takeaways

The computed pattern calculates new fields from existing data dynamically in MongoDB.
It uses aggregation stages like $addFields or $project to create computed fields.
This pattern avoids storing redundant data and keeps your database clean.
Ideal for on-the-fly calculations such as totals, averages, or conditional logic.
Helps maintain data accuracy by computing values when needed instead of storing them.