Question

I have a model in a Rails 4.0.3 app which uses Mongoid 4 (master branch directly from GitHub), and I'm trying to ensure an index on multiple fields to be unique and to drop duplicates.

class MyModel
  include Mongoid::Document  

  field :a, type: Integer
  field :b, type: Integer

  index({a: 1, b: 1}, {unique: true, dropDups: true, name: 'unique_drop_dups_idx'})

But when I run the command to create indexes:

 rake db:mongoid:create_indexes

I get this error:

Problem:
  Invalid index specification on MyModel: {:a=>1, :b=>1}, {:unique=>true, :dropDups=>true, :name=>"unique_drop_dups_idx"}
Summary:
  Indexes in Mongoid are defined as a hash of field name and direction/2d pairs, with a hash for any additional options.
Resolution:
  Ensure that the index conforms to the correct syntax and has the correct options.

The index creation starts if I get rid of the dropDups option, even if it fails eventually because of the presence of duplicates.

Does the error message means that is not possible to create an index on multiple fields with this configuration (unique + dropDups)? Am I missing something else?

Was it helpful?

Solution

dropDups is not a valid index option for mongoid. You need to use drop_dups instead.

 index({a: 1, b: 1}, {unique: true, drop_dups: true, name: 'unique_drop_dups_idx'})

We try not to use camel case for options as we are on ruby land. You can see the mappings in here https://github.com/mongoid/mongoid/blob/master/lib/mongoid/indexable/specification.rb#L14.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top