tufla
tufla

Reputation: 562

How to get new mongoid indexes for a model

Let's say I have defined my model Person with a couple of indexes:

class Person
  include Mongoid::Document
  field :email
  field :ssn

  index({ email: 1 }, { unique: true })
  index({ ssn: 1 }, { unique: true })
end

However, only the email index already exists in the database, so when I call

Person.collection.indexes.each {|i| puts i.inspect}

I get the following response:

{"v"=>1, "key"=>{"_id"=>1}, "name"=>"_id_", "ns"=>"x.person"}
{"v"=>1, "unique"=>true, "key"=>{"email"=>1}, "name"=>"email_1", "ns"=>"x.person"}

The question is, how can I get the list of defined indexes in the model, even if they are not already created in mongo ?

In my case, such list should include the definition for the field "ssn"

In other words...How to get those indexes that haven't been created yet ?

Upvotes: 2

Views: 3822

Answers (2)

liukgg
liukgg

Reputation: 236

Person.index_specifications 

shows the indexes defined in the model regardless of its existence in the database.

And

Person.collection.indexes

only shows the index that actually exists in the database.

So there is something else that is worth paying attention to:

rake db:mongoid:create_indexes 

will create the indexes defined in the model in the database, and it uses the method 'index_specifications' in deed.

While this removes all the indexes other than the index of the primary key:

rake db:mongoid:remove_indexes 

So when you want to only remove the indexes that exists in the database but no longer defined in the database, you should use this:

rake db:mongoid:remove_undefined_indexes

which use the method 'undefined_indexes' in deed.

I hope this can be helpful.

The docs are here:

https://mongoid.github.io/en/mongoid/docs/indexing.html

http://www.rubydoc.info/github/mongoid/mongoid/Mongoid/Tasks/Database#create_indexes-instance_method

Upvotes: 7

tufla
tufla

Reputation: 562

Just found it...

We can get the list of all index definitions into the model as follows:

Person.index_specifications

This is an array populated when the application is loaded and is used by the "create_indexes" method as can be seen here:

https://github.com/mongodb/mongoid/blob/master/lib/mongoid/indexable.rb

Upvotes: 0

Related Questions