11
votes

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.

2
what version of mongoid are you using? - Miguel Ping

2 Answers

7
votes

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.

0
votes

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 .