Mongoid (MongoDB) has_many/belongs_to relation and wrong index being picked

Sometimes when you have a belongs_to relations, you may notice, that getting an owner object can be really slow. Even if you add index like this:

Mongoid might not catch it. Unfortunately you can’t just explain it, since this relation is returning an object not a Mongoid::Criteria. Luckily you can just hook up to your slow-log and grep for it (or you can just benchmark it). Either way, if you notice that it’s not using index as it should, first declare it the way it should be declared:

If you already had an index on a person_id, you don’t need to recreate it. It should use it out of the box. If it doesn’t help, you can always use explain to overwrite the default finder method for this relation: