Computed Pattern

noun

say it: “kum-PYOO-tid PAT-ern” /kəmˈpjutɪd ˈpætərn/

A data design that calculates a value, such as a total or a count, when data is saved and stores it, instead of calculating it on every read.

What is the computed pattern?

The computed pattern works a number out when the data is written and stores it, such as a product's review count and star total, kept up to date with $inc. Every page that shows the average reads two fields instead of adding up every review.

db.products.updateOne({ _id: 7 }, { $inc: { reviewCount: 1, starTotal: 4 } });
const helmet = db.products.findOne({ _id: 7 });
helmet.starTotal / helmet.reviewCount;   // 4.5

In a sentence

  • “The computed pattern keeps each product's review count in the product, so the list page never counts reviews.”
  • “With the computed pattern, adding a review runs one $inc as well as the insert.”

Level: Journeyman · More MongoDB terms at this level

Updated