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

Model with inheritance and has_one relation cause extra query

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

      Had to debug a performance issue that broke our app yesterday.

      Turned out it was due to Mongoid making a non wanted query (on a non indexed field) when requesting a belongs_to association with a reverse has_one declaration.

      Reproduce on Mongoid 3.1.2 with:

      class Video
        include Mongoid::Document
      
        belongs_to :screenshot
      end
      
      class Image
        include Mongoid::Document
      end
      
      class Screenshot < Image
        has_one :video
      end
      
      Video.delete_all
      Screenshot.delete_all
      
      Video.create(screenshot: Screenshot.create)
      
      video = Video.last
      
      Moped.logger = Logger.new($stdout)
      
      video.screenshot
      
      # Normal query: MOPED: 127.0.0.1:27017 QUERY        database=analytics_test collection=images selector={"$query"=>{"_id"=>"516e3cbac3b5a07a2c000001", "_type"=>{"$in"=>["Screenshot"]}}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields=nil (0.4778ms)
      # Extra query: MOPED: 127.0.0.1:27017 QUERY        database=analytics_test collection=vs selector={"$query"=>{"screenshot_id"=>"516e3cbac3b5a07a2c000001"}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields=nil (0.2599ms)
      

      Without the has_one declaration the extra query disappears:

      # ... class definitions ...
      
      class Screenshot < Image
        # has_one :video <- removed this
      end
      
      # ... object stuff ...
      
      video.screenshot
      
      # Normal query only: MOPED: 127.0.0.1:27017 QUERY        database=analytics_test collection=images selector={"$query"=>{"_id"=>"516e3cbac3b5a07a2c000001", "_type"=>{"$in"=>["Screenshot"]}}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields=nil (0.4778ms)
      

      We survived by adding an index on screenshot_id. But I guess that query should never have happened in the first place.

            Assignee:
            durran Durran Jordan
            Reporter:
            dbackeus David Backeus
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: