【发布时间】:2015-01-11 03:29:23
【问题描述】:
我目前有一个 Comment MongoDB 表,我在其中强制 remote_id 字段的唯一性。
The MongoDB documentation is here.
我现在处于remote_id 属性应该只对拥有评论的用户唯一的情况。换句话说:
-
UserPeter只能有1个Comment和remote_id123 -
UserJohn只能有1个Comment和remote_id123 -
UsersPeter 和 John 都可以有 1 个Comment和remote_id123
如何强制 2 个字段组合的唯一性?
我的表是在我的 Ruby on Rails 应用程序中的模型文件中定义的,它目前看起来像这样:
class Comment
include Mongoid::Document
include Mongoid::Timestamps
field :datetime, type: Time
field :remote_id, type: String
index({ remote_id: 1 }, { unique: true })
index({ user_id: 1 }, { background: true })
belongs_to :user, :inverse_of => :comments
end
【问题讨论】:
-
我对Ruby一无所知,但您正在寻找的是一个独特的复合索引,它是在mongo shell中使用
db.collection.ensureIndex({user_id:1,remote_id:1},{unique:true})创建的。 -
@MarkusWMahlberg Mongoid 的
index调用几乎直接转换为ensureIndex,所以index(x)最终变成ensureIndex(x)。即使不了解 Ruby,您也非常接近答案。 -
大家好。感谢您的参与。但是你们是说我的代码中当前为
index({ remote_id: 1 }, { unique: true })的索引可能是index({ remote_id: 1, user_id: 1 }, { unique: true })吗? -
是的,应该可以。如果马库斯回答我会更舒服。
-
我刚刚测试过,它确实有效。多谢你们。随意把它作为答案。
标签: ruby-on-rails mongodb mongoid