Schema for User Ratings - Key/Value DB

前端 未结 4 1044
暖寄归人
暖寄归人 2021-02-02 18:15

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 from
4条回答
  •  眼角桃花
    2021-02-02 18:40

    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).

    The Results is:

    • rateCount now is sum of each item in array.
    • rateAverage should be (index+1 * value) / rateCount.
    • We can get total number rate by value mapping with index + 1 too.

    Step by step

    For default, this should be:

    // Book Document
    {
     _id,
     totalRated: [0, 0, 0, 0, 0],
     ...otherFields
    }
    
    • If user1 rate 5 star for this book, the document now should be:
    {
     _id,
     totalRated: [0, 0, 0, 0, 1],
     ...otherFields
    }
    
    • If user2 rate 4 star for this book, the document now should be:
    {
     _id,
     totalRated: [0, 0, 0, 1, 1],
     ...otherFields
    }
    
    • If user3 rate 4 star for this book, the document now should be:
    {
     _id,
     totalRated: [0, 0, 0, 2, 1],
     ...otherFields
    }
    
    • rateCount = 0 + 0 + 0 + 2 + 1 = 3
    • rateAverage = (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.

提交回复
热议问题