Skip to main content

Computed Pattern

Use Case:

  • running a function frequently degrade performance, for example: calculate the average rating whenever a new review is submitted.
    • Mathematical Operation: store avg and # of reviews. then update the rating: (avg_rating * #reviews + new_rating) / (#reviews + 1)
      • one insert (the new review) and one update (to the book document)
    • Roll-Up Operation: Do the computation in time intervals (for example, daily)

Roll-Up Example:

use bookstore:
var roll_up_product_type_and_number_of_authors_pipeline = [
  {
    $group: {
      _id: "$product_type",
      count: {
        $sum: 1,
      },
      averageNumberOfAuthors: {
        $avg: {
          $size: "$authors",
        },
      },
    },
  },
]

db.books.aggregate(roll_up_product_type_and_number_of_authors_pipeline)

// Sample Output:
[
  { _id: 'audiobook', count: 1, averageNumberOfAuthors: 1 },
  { _id: 'ebook', count: 1, averageNumberOfAuthors: 3 },
  { _id: 'book', count: 1, averageNumberOfAuthors: 3 }
]

  • The $sum operator increments the count of books for each type. The $size operator gets the number of authors in the authors array which is then averaged for the type using the $avg operator.