【问题标题】:Avoiding Mongoid N+1避免 Mongoid N+1
【发布时间】:2012-12-06 20:21:02
【问题描述】:

我想拉出所有至少有一个“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})

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    为了避免 N+1 问题启用 Mongoid identity_map feature

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

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

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

    【讨论】:

    • 完美。如果一家公司也有许多行业(每个行业都有一个名称字段),那么最好的链接方式是什么? (例如“娱乐”的行业名称)?
    • 丑陋(仍然保持关系会很好)但有效......:Position.where(title: /.*CEO.*/).includes(:company).map( &:company).select{ |co| co["industry_id"]==Industry.find_by(name: "Entertainment")["_id"]}
    • 我会尝试类似entertainment_ids = Position.where(title: 'CEO').includes(:company).map(&:company).map(&:entertainment_id); Entertainment.find(entertainment_ids) 的方法 - 这将在 3 个查询中执行,而不是 N+1。请为答案投票
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 2015-11-28
    • 2012-05-19
    • 2011-12-07
    • 2011-07-12
    • 2019-03-16
    • 1970-01-01
    相关资源
    最近更新 更多