避免Mongoid N + 1

时间:2012-12-06 20:21:03

标签: ruby-on-rails mongodb mongoid

我想拉出所有至少有一个职位头衔的公司#34; CEO"。

我可以将它与每个表和一个交叉点的查询一起破解(我知道......没有加入http://mongoid.org/en/mongoid/docs/tips.html#relational_associationsN+1 problem in mongoid,我可以在公司中嵌入职位),但任何做某事的方法:

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

感谢:

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

1 个答案:

答案 0 :(得分:1)

要避免N + 1问题,请启用Mongoid identity_map feature

这将允许您执行以下查询:

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

哪个应该只对数据库执行2次查询。