学习RoR和Mongo,为什么不统计数组求票数

发布于 2024-09-08 08:16:50 字数 688 浏览 5 评论 0原文

我对 Mongo 和 RoR 完全陌生,有 PHP 背景。

我刚刚浏览了有关数据建模的教程 http://www.mongodb.org/display/DOCS/ MongoDB+Data+Modeling+and+Rails

并被一个问题所震惊:为什么教程会建议将投票存储在一个字段中并将该字段更新为

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}});

然后数然后

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

我知道这是一个教程,但它似乎不是管理数据的最有效方法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

超可爱的懒熊 2024-09-15 08:16:50

本教程可以通过解释维护计数缓存字段(投票)的目的来做得更好,因为只有当您打算对数组大小进行范围查询时才需要它。

来自文档

您不能使用 $size 来查找范围
大小(例如:数组
超过 1 个元素)。如果您需要
查询一个范围,创建一个额外的
大小字段,当您
添加元素。

将来,随着查询功能的不断增长,我们可能不必这样做。请参阅 JIRA 票证 SERVER-478

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文