mongoid 7.1 / mongo 4.0 eager loading is not working

Viewed 103

I have two models, case and case status

class Case
    has_many :case_statuses, dependent: :destroy
    ...

class CaseStatus
    belongs_to :case, index: true, inverse_of: :case_statuses

Using .includes in a query seems to have no impact on the number of mongo queries that fire.

ids = [# 10 random ids]

# this fires 11 queries
Case.where(:id.in => ids).includes(:case_statuses).collect{|x| x.case_statuses.count}

# this also fires 11 queries
Case.where(:id.in => ids).collect{|x| x.case_statuses.count}

Am I doing something wrong? My expectation when reading the Mongoid 7 docs was that eager loading would result in 1 query.

Thanks for any help, Kevin

1 Answers

the problem here is that count triggers a query to the db, you can use size to avoid that behavior.

Case.where(:id.in => ids).includes(:case_statuses).collect{|x| x.case_statuses.size}

Also, mongodb does not support querying associations as mosts sql db does, so you cannot narrow it down to just 1 query with this approach, you will have at least 1 query for each nested assotiation.

you can always get a single query if you use the aggregation pipeline

Related