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:

class Activity
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic
 
  belongs_to :person

  index({ person_id: 1 }, background: true)
end

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:

class Activity
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic
 
  belongs_to :person, index: true
end

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:

class Activity
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic
 
  belongs_to :person, index: true

  def person
    # Here in explain you need to provide index name
    @person ||= Person.hint('person_id_1').find_by(person_id: person_id)
  end
end

Note: this post might be somehow related to this issue.