user3576036
user3576036

Reputation: 1425

How to add index in a rails app with mongodb/mongoid

I am new to Mongodb. I know how to add indexing in Mysql for a active record rails app. I am justing trying to learn the mongo way to do it.

I am generating a user model with following fields.

rails g model User provider:string uid:string name:string location:string image_url:string url:string

In Mysql the indexing I needed to add to the migration file was as follows

443343_create_users.rb

t.string :provider, null: false
t.string :uid, null: false
add_index :users, :provider
add_index :users, :uid
add_index :users, [:provider, :uid], unique: true

How do I achieve same in the User model created using mongoid

class User
  include Mongoid::Document
  field :provider, type: String
  field :uid, type: String
  field :name, type: String
  field :location, type: String
  field :image_url, type: String
  field :url, type: String
end

Upvotes: 2

Views: 3720

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230276

With mongoid you define indexes in the model class.

class User
  include Mongoid::Document

  field :provider, type: String
  field :uid, type: String

  index({ provider: 1, uid: 1 }, { unique: true})
end

Then you can run this command to create all missing indexes (present in the models but not the database)

rake db:mongoid:create_indexes

Upvotes: 4

Related Questions