Storing “votes” in a database

后端 未结 5 384
既然无缘
既然无缘 2021-02-02 16:44

I\'m writing what will be an intranet application, and one of its features is roughly analogous to content voting - not unlike what SO, Amazon, and many other sites do.

5条回答
  •  情歌与酒
    2021-02-02 17:23

    I'd say you need to figure out how these votes will be used and design specific queries for your data model first. This is not necessarily SQL model. If you're coming from SQL world, passing through official MongoDB tutorial helps to clear the mind for the start.

    For example, if you only need to store and display votes for a single issue page, it may be convenient to store votes in a single string field of the issue, which will look like id1:id2:id3:. Assuming all ids are of the same length, there are some interesting properties:

    1. Count all votes for the issue:

      len(issue.votes)/len(id)

    2. Find I voted on the issue

      myid in issue.votes

    3. Find all issues you voted on:

      select issue.id from issues where issue.votes contains(myid)

    4. Find the most voted issues

      select issue.id from issues order by len(issue.votes) desc limit 10

    This architecture allows to avoid expensive calculations on read in these specific cases, but updating issue.votes on vote might be more expensive than adding a row in a table. In this case 100 votes with 4 bytes per id + separator is 500 bytes string. In your proposed variant 100 votes are 800 bytes.

    Disclaimer: I never implemented anything like this, it is just an idea.

提交回复
热议问题