Mongo数据建模/投票更新(上下) [英] Mongo data modeling/updates for voting (up and down)

查看:68
本文介绍了Mongo数据建模/投票更新(上下)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Mongo中有一个有关投票数据模型/更新查询的示例:
http://www.mongodb.org/display /DOCS/MongoDB + Data + Modeling + and + Rails#MongoDBDataModelingandRails-AtomicUpdates

There is an example on voting data model/update queries in Mongo:
http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails#MongoDBDataModelingandRails-AtomicUpdates

但是我同时需要上下投票(基本上,一个人可以投赞成票或投反对票).另外,我希望选民能够改变主意,将赞成票改为反对票(反之亦然)(因此,选民名单和总数不适合).

However I need both up and down votes (basically, one person can either cast up vote or down vote). Also, I want for voter to be able to change his mind and change upvote to downvote or vice-versa (so the list of voters and total number does not fit).

最好的数据模型和相应的更新调用是什么?

What would be the best data model and corresponding update call?

我看到两种可能性,要么做一次

I see two possibilities, either do a

'votes': [{ 'user_id' : ... , 'vote': ±1 }]

'upvoters': [...], 'downvoters': [...]

但是我还不能对第一个查询更新查询,而第二个查询看起来有点奇怪(尽管可能只是我一个人).

But I can't make an update query for the first one yet, and second one looks a bit weird (though it may be just me).

推荐答案

第一个架构看起来不错.第二种模式很难,因为当用户单击"upvote"而不是"downvote"时,您需要将"userId"添加到"upvoters"中,然后再添加到"downvoters"中,并从"upvoters"中删除,反之亦然.

First schema looks like good. Second schema is hard because when user click upvote and than downvote you need add userId to 'upvoters' that to 'downvoters' and remove from 'upvoters' and vice versa.

我想把它投给某些文件而不是它的收藏(假设它是问题).

I suppose votes it nestead collection of some document(suppose it questions).

db.questions.update({votes.userId: .. },{ $set : { votes.$.vote : 1 } });//upvote
db.questions.update({votes.userId: .. },{ $set : { votes.$.vote : -1 } });//down

似乎您需要在问题集合中创建额外的字段来计算上下表决的总和:

And seems you need create extra field inside of questions collection to calculate sum of up/down votes:

db.questions.update({_id: .. },{ $inc : { votesCount : 1 } }); //up vote
db.questions.update({_id: .. },{ $inc : { votesCount : -1 } }); // down vote

如果您需要将新用户添加到投票列表中,请使用

If you need add new user to array of votes use

位置运算符.

这篇关于Mongo数据建模/投票更新(上下)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆