Databases Reference
In-Depth Information
Voting
There are many ways of implementing voting, depending on the functionality and in-
formation you want: do you allow up and down votes? Will you prevent users from
voting more than once? Will you allow them to switch their vote? Do you care when
people voted, to see if a link is trending? Each of these requires a different solution with
far more complex coding than the simplest way of doing it: using "$inc" :
$posts->update(array("_id" => $postId), array('$inc' => array("votes", 1)));
For a controversial or popular link, we wouldn't want people to be able to vote hun-
dreds of times, so we want to limit users to one vote each. A simple way to do this is
to add a "voters" array to keep track of who has voted on this post, keeping an array
of user "_id" values. When someone tries to vote, we do an update that checks the user
"_id" against the array of "_id" values:
$posts->update(array("_id" => $postId, "voters" => array('$ne' => $userId)),
array('$inc' => array("votes", 1), '$push' => array("voters" => $userId)));
This will work for up to a couple million users. For larger voting pools, we would hit
the 4MB limit, and we would have to special-case the most popular links by putting
spillover votes into a new document.
Custom Submission Forms: Ruby
MongoDB is a popular choice for Ruby developers, likely because the document-
oriented approach meshes well with Ruby's dynamism and flexibility. In this example
we'll use the MongoDB Ruby driver to build a framework for custom form submissions,
inspired by a New York Times blog post about how it uses MongoDB to handle
submission forms ( http://open.blogs.nytimes.com/2010/05/25/building-a-better-submis
sion-form/ ) . For even more documentation on using MongoDB from Ruby, check out
the Ruby Language Center .
Installing the Ruby Driver
The Ruby driver is available as a RubyGem, hosted at http://rubygems.org . Installation
using the gem is the easiest way to get up and running. Make sure you're using an up-
to-date version of RubyGems (with gem update --system ) and then install the
mongo gem:
$ gem install mongo
Successfully installed bson-1.0.2
Successfully installed mongo-1.0.2
2 gems installed
Installing ri documentation for bson-1.0.2...
Building YARD (yri) index for bson-1.0.2...
Installing ri documentation for mongo-1.0.2...
Building YARD (yri) index for mongo-1.0.2...
 
Search WWH ::




Custom Search