在 MongoDB shell 中,如果我执行以下操作,则会创建一个索引,并防止插入重复记录:
db.analytics.ensureIndex({page: 1, some_id: 1, ga_date: -1}, {unique: true});
但我认为 Mongoid 也可以这样做: http ://mongoid.org/docs/indexing/
所以我有:
class PageAnalytic < Analytic
include Mongoid::Document
field :page, :type => String
field :some_id, :type => Integer
field :ga_date, :type => Time
field :pageviews, :type => Integer
field :timeOnPage, :type => Integer
index(
[
[ :page, Mongo::ASCENDING ],
[ :some_id, Mongo::ASCENDING ],
[ :ga_date, Mongo::DESCENDING ]
],
:unique => true
)
end
并做一个
rake db:create_indexes
但是仍然可以插入重复记录吗?
更新:这很奇怪,但是在我在 MongoDB shell 中添加索引并删除集合之后,然后在 MongoDB Shell 或 Mongoid 中重新创建索引,现在我可以在 MongoDB shell 中删除集合,然后 rake 创建index,并使用 mongoid 两次添加相同的文档,mongod 会说重复键错误。