Computed pattern to store average for most recent N documents

I have a collection that stores products.

Each product can be rated by users.

There will be another collection to hold the ratings of products by users.

In the products collection, there will be a field to store the average of the last N rating.

The ratings collection will be indexed by date added, of course.

  • option 1 - when a new rating is added for a product, go to the ratings collection, retrieve the last N ratings, compute the average and then replace the current average in the products collection.

  • option 2 - store an array of the last N ratings in a field of the products collection. When a new rating is added, push this into this array, pop out the oldest, and then compute the average from this array.

  1. Assuming that N is small, what is the trade off between the two options above?
  2. Assuming that N is large, is option 2 still viable?

Option three - don’t worry about this happening in real time/synchronously and just update the average periodically… It all depends on how many ratings are coming in, how fast, do you have other uses for most recent ratings inside products, etc.

Asya