1

I'm creating a React firebase website that has a collection of documents that contains a rating from 1 to 10. All of these documents have an author attached. The average rating of all of the author's documents should be calculated and presented.

Here are my current two solutions:

  1. Calculate the average from all the documents with the same author

  2. Add the statistic to the author himself, such that every time the author adds a new document it will update his statistic

My thought process of the second one is such that the website doesn't have to calculate the average rating each time it's requested. Would this be a bad idea, or isn't there a problem in the first place, reading all the documents and calculating in the first place?

Casper Jensen
  • 65
  • 1
  • 6

1 Answers1

3

Your second approach is in fact a best practice when working with NoSQL databases. If you calculate the average on demand across a dynamic number of documents, the cost of that operation will grow as you add more documents to the database.

For this reason you'll want to calculate all aggregates on write, and store them in the database. With that approach looking up an aggregate value is a simple write.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807