Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why MongoDB can create unique index but Mongoid cannot?

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 still, 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.

like image 491
nonopolarity Avatar asked Sep 15 '10 23:09

nonopolarity


1 Answers

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.

like image 141
agate Avatar answered Sep 19 '22 20:09

agate