We\'re using MongoDB and I\'m figuring out a schema for storing Ratings.
from
My solution is quite simple, similar to your 3rd option but more simpler. Let's said we have 3 models: Book, User and Rating. I added new field call totalRated - array of int to Book model to store total Rated counting, the value is mapping index + 1.
Your rating system from 1-5, so, totalRated means:
[total1star, total2star, total3star, total4star, total5star]Every time user rate this Book, I will create a Document on Rating collection, and increase the counting by 1 (mapping with the index+1 of totalRated array).
rateCount now is sum of each item in array.rateAverage should be (index+1 * value) / rateCount.index + 1 too.For default, this should be:
// Book Document
{
_id,
totalRated: [0, 0, 0, 0, 0],
...otherFields
}
{
_id,
totalRated: [0, 0, 0, 0, 1],
...otherFields
}
{
_id,
totalRated: [0, 0, 0, 1, 1],
...otherFields
}
{
_id,
totalRated: [0, 0, 0, 2, 1],
...otherFields
}
0 + 0 + 0 + 2 + 1 = 3(0*1 + 0*2 + 0*3 + 2*4 + 1*5)/3 = 9.6666...Note: You can change array int to array object, the key should be rating value, and value should be totalRating, but array int is enough for me.