dboyd68
dboyd68

Reputation: 1104

mongoid index on polymorphic collection

Trying to work out the best way to add an index on a polymorphic association in mongoid

I have

class User
  include Mongoid::Document

class Student < User
  include Mongoid::Document

class Parent < User
  include Mongoid::Document

when mongoid creates data it creates a _type field

Parent
{
"_id" : ObjectId("51f06367b5b60561d0000003"),
"_type" : "Parent"
}

I want to search on type. e.g. Student.all and noticed with the explain() there is no implict index created by mongoid.

To solve this I added an index in the User class

index({ _type: 1 })

Wondering is there a way to get mongoid to create index's automatically? Or is there a better way to do this apart from adding the index on the User model?

Upvotes: 2

Views: 383

Answers (1)

Joost Baaij
Joost Baaij

Reputation: 7598

What you have here is a subclass, not polymorphism as mentioned in the Mongoid documentation. But, there is no automated way. Adding the index manually is the recommended approach, so you're all set!

http://mongoid.org/en/mongoid/v3/documents.html#inheritance

Upvotes: 1

Related Questions