Learning RoR and Mongo, why not count an array of votes

I am completely new to Mongo and RoR, coming from the background of PHP.

I just went through this data modeling tutorial http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails

and was amazed at the question of why the textbook would recommend storing votes in the field and updating this field as

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

and then counting

  Story.voters.count
to find out the number of users who voted?

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

+4
source share
1 answer

The tutorial could improve the work by explaining the purpose of maintaining the cache (count) cache field, since this is only necessary if you intend to make range requests for the size of the array.

From documents :

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

In the future, we probably will not have to do this, as the query capabilities continue to grow. See JIRA SERVER-478 Ticket.

+1
source

Source: https://habr.com/ru/post/1314461/


All Articles