views:

68

answers:

1

I'm completely new to Mongo and RoR, coming from a PHP background.

I was just going through this tutorial about data modelling http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails

and was struck with the question of why the tutorial would recommend storing the votes in a field and updating that field as

db.stories.update({_id: story_id, voters: {'$ne': user_id}}, 
  {'$inc': {votes: 1}, '$push': {voters: user_id}});
instead of just

db.stories.update({_id: story_id, voters: {'$ne': user_id}}, 
  {'$push': {voters: user_id}});

and then counting then

Story.voters.count
to get the count of the number of users who have voted?

I know it's a tutorial, but it doesn't seem like the most efficient way to manage the data.

+1  A: 

The tutorial could do a better job by explaining the purpose of maintaining the count cache field (votes), since it's only needed if you intend to do range queries on the array's size.

From the docs:

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.

In the future we probably won't have to do that as the query capabilities continue to grow. See JIRA ticket SERVER-478.

Jim Garvin