Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-2177

Eager loading does not prevent subsequent individual finds if there was no related document

    • Type: Icon: Task Task
    • Resolution: Done
    • 3.0.0
    • Affects Version/s: None
    • Component/s: None

      When using eager loading, only existing related documents are added to the identity map. This may sound like exactly what you'd want but in fact presents problems when lots of parent documents don't have any related documents. Consider the below:

      class A
        include Mongoid::Document
        belongs_to :b
      end
      
      class B
        include Mongoid::Document
        has_one :a
      end
      
      5.times { B.create }
      A.create(:b => B.last)
      
      Mongoid.identity_map_enabled = true
      
      B.all.includes(:a).collect(&:a)
      

      In that example, 6 queries will be executed:

      (1) Find all Bs – perfectly fine
      (2) Find all As with matching b_ids – perfectly fine
      (3)–(6) For all Bs with no matching A, try to find it again because the identity map does not store nil objects – potentially huge performance problem

      Not sure if this is worth "fixing", or on what level that should be done (identity map or relations), but if it's a wontfix, I would suggest adding it as a potential caveat to the docs.

            Assignee:
            Unassigned Unassigned
            Reporter:
            niels Niels Ganser
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: