views:

106

answers:

0

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.