Doug
Doug

Reputation: 283

Avoiding Mongoid N+1

I'd like to pull all companies that have at least one position title of "CEO".

I could hack it together with a query for each table and an intersect (I know... no joins http://mongoid.org/en/mongoid/docs/tips.html#relational_associations, and N+1 problem in mongoid, and I could just embed positions in company), but any way to do something like:

Company.includes(:positions).where("positions.title" => "CEO")?

Thanks:

class Position
  include Mongoid::Document

  field :title, type: String
  field :profile_id, type: String
  field :tenure, type: BigDecimal

  belongs_to :company, index: true

class Company
  include Mongoid::Document

  field :name, type: String
  field :linkedin_id, type: String
  field :positions_count, type: Integer #Mongo Index

  belongs_to :industry, index: true
  has_many :positions

  index({ positions_count: 1}, {background: true})

Upvotes: 0

Views: 918

Answers (1)

Alon Burg
Alon Burg

Reputation: 2550

To avoid the the N+1 problem enable Mongoid identity_map feature

This will allow you to do the following query:

companies_with_ceo = Position.where(title: 'CEO').includes(:company).map(&:company)

Which should execute only 2 queries to the database.

Upvotes: 1

Related Questions