开发者

Why MongoDB can create unique index but Mongoid cannot?

开发者 https://www.devze.com 2023-01-16 03:30 出处:网络
In the MongoDB shell, if I do the following, then an index is created, and also prevent duplicate records from being inserted:

In the MongoDB shell, if I do the following, then an index is created, and also prevent duplicate records from being inserted:

db.analytics.ensureIndex({page: 1, some_id: 1, ga_date: -1}, {unique: true});

But I thought Mongoid can do the same: http://mongoid.org/docs/indexing/

So I have:

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

and do a

rake db:create_indexes

but stil开发者_运维技巧l, duplicate records can be inserted?

Update: it is quite strange, but after I added the index in the MongoDB shell and dropping the collection, and then recreated the index either in the MongoDB Shell or Mongoid, now I can drop the collection in MongoDB shell, and then rake create the index, and use mongoid to add the same documents twice, and mongod will say error for duplicate key.


Did you use the normal way to save your model? Like:

page_analyitc.save

If you use this way to save model, mongoid won't give any error message.(if there have a duplicate key on mongodb)

So the correct way to do this is using:

page_analyitc.safely.save

It will raise an error like:

Mongo::OperationFailure: 11001: E11001 duplicate key on update

Hope these information can help you.


When you add a index in your document, mongoid wont create any index automagically. In order to create the index, you need to run the rake task rake db:mongoid:create_indexes as you can see in the new docs http://mongoid.org/en/mongoid/docs/indexing.html .

0

精彩评论

暂无评论...
验证码 换一张
取 消