Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple voting system with MongoDB

Tags:

mongodb

quick question I have a list of articals in mongodb and I want users to be able to upvote or down vote the artical.

My first way would be in the artical collection to have two rows called upvote and downvote they would have numbers like upvote:360 downvote:102;

then I would need to order this by doing a sum upvote-downvote this would show the total likes of the artical.

My question is in the mongoDB is this the best way to do it or am I better off with one "vote" and then just order it by that vote.

Thank You

like image 580
RussellHarrower Avatar asked Sep 09 '12 12:09

RussellHarrower


1 Answers

When you would do it that way, you wouldn't track which user has already voted, so users can vote multiple times. That's surely not in your interest.

For that reason I would add an array "votes" to each article which includes an object for each vote which uniquely identifies the user who made it:

votes: [ 
        { voter:"name or ID or IP address or some other unique identifier for the person who voted",
          vote:-1 },
        { voter:"someone else",
          vote:1 },
        { voter:"and someone entirely different",
          vote:-1 }
    ]

When you create an unique index over the article ID and votes.voter, you have already ensured that nobody can vote twice for an article.

When you use a value of "-1" for downvote and "1" for upvote you can calculate the total score of an article by using the $sum aggregate function (It would also easily allow you to introduce weighted votes later, when you feel like it).

like image 75
Philipp Avatar answered Nov 12 '22 02:11

Philipp