简体   繁体   中英

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})

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM