I've been working on a site that implements rating movies with cloud firestore. Currently I have a ratings collection with every rating. Within each document contains the rating, user id, and the movie id. When a user accesses the movie's page I would like to show where the movie ranks on their list. I did this using a query that searches the ratings collection for the current users id. The issue with this solution is that if a user rates a lot of movies (e.g. 500), the site will read 500 documents each time its loaded, which could get expensive quickly. Is there any other way to do this?
Asked
Active
Viewed 625 times
1 Answers
1
If all the data you have is exactly as you have described, you don't have a way to query for just what you want. Firestore doesn't offer any SQL-like aggregation functions like sum() and avg(), so you will, in fact, need to query all of those documents and do math on the client to find the ranks.
If you don't want to read all of these documents every time, you will need to write code to maintain documents with aggregate data that get updated with every new and updated rating. So, if a user wants to add a new rating, you will have to write code that makes sure the rating document gets added, and also the aggregate document maintains whatever ranking you want to pre-compute.

Doug Stevenson
- 297,357
- 32
- 422
- 441