Indexes¶
You can define indexes on documents using the index macro. Provide the key for the index along with a direction. For additional options, supply them in a second options hash parameter.
You can define indexes on embedded document fields as well.
You can index on multiple fields and provide direction.
Indexes can be sparse:
Indexes can be run in the background in cases where they may take some time:
Deprecated: When using MongoDB 2.6, you can drop the duplicate entries
for unique indexes that are defined for a column that might
already have duplicate values by specifying the drop_dups
option:
The drop_dups
option has been removed as of MongoDB 3.0.
For geospatial indexes, make sure the field you are indexing is an Array.
Indexes can be scoped to a specific database.
You can have Mongoid define indexes for you on “foreign key” fields for relational associations. This only works on the relation macro that the foreign key is stored on.
When you want to create the indexes in the database, use the provided rake task.
Mongoid also provides a rake task to delete all secondary indexes.
Note: the output of these rake tasks goes to the default logger configured
by Rails. This is usually a file like log/development.log
and not standard
output.
These create/remove indexes commands also works for just one model by running
or