We're using MongoDB and I'm figuring out a schema for storing Ratings.
- Ratings will have values of 1-5.
- I want to store other values such as
fromUser
This is fine but the main question I have is setting it up so that recalculating the average is as efficient as possible.
SOLUTION 1 - Separate Ratings Class
The first thought was to create a separate Ratings
class and store an array of pointers to Ratings
in the User
class. The reason I second guessed this is that we will have to query for all of the Ratings
objects every time a new Rating
comes in so that we can recalculate an average
...
SOLUTION 2 - Dictionary in User Class
The second thought was to store a dictionary in the User
class directly that would store these Ratings
objects. This would be slightly more lightweight than Solution 1, but we'd be re-writing the entire Ratings
history of each user every time we update. This seems dangerous.
...
SOLUTION 3 - Separate Ratings Class with Separate Averages in User Class
Hybrid option where we have Ratings
in their own class, and a pointer array to them, however, we keep two values in the User Class - ratingsAve
and ratingsCount
. This way when a new Rating is set we save that object but we can recalculate the ratingsAve
easily.
SOLUTION 3 sounds best to me but I'm just wondering if we'd need to include periodic calibrations by requerying the Ratings history to reset the ratingsAve
just to make sure everything checks out.
I might be overthinking this but I'm not that great at DB schema creation, and this seems like a standard schema issue that I should know how to implement.
Which is the best option to ensure consistency but also efficiency of recalculation?