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

Eager loading loads unnecessary documents when multiple associations reference the same model class

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • 8.0.1
    • Affects Version/s: 5.1.4
    • Component/s: Query
    • Minor Change

      A criteria with eager loading like

      Blog.includes(:posts, :highlighted_post => :author)
      

      will eagerly load all the authors for each post in `posts` despite only requesting the author of `highlighted_post`.

      Concretely, given the models

      class Blog
        has_and_belongs_to_many :posts
        belongs_to :highlighted_post, class_name: "Post"
      end
      
      class Post
        belongs_to :author
      end
      
      class Author
      end
      

      and seed data

      Blog.create(
        posts: [
          Post.create(author: Author.create),
          Post.create(author: Author.create),
          Post.create(author: Author.create),
        ],
        highlighted_post: Post.create(author: Author.create)
      )
      

      the code

      Blog.includes(:posts, :highlighted_post => author)
      

      generates the queries

      db.find | STARTED | {"find"=>"blogs", "filter"=>{}}
      db.find | SUCCEEDED | 0.000409s
      db.find | STARTED | {"find"=>"posts", "filter"=>{"_id"=>{"$in"=>[BSON::ObjectId('57d4c58e3e9d19784e191080'), BSON::ObjectId('57d4c5913e9d19784e191081'), BSON::ObjectId('57d4c5953e9d19784e191082')]}}}
      db.find | SUCCEEDED | 0.00045s
      db.find | STARTED | {"find"=>"posts", "filter"=>{"_id"=>{"$in"=>[BSON::ObjectId('57d4c99a3e9d19784e191085')]}}}
      db.find | SUCCEEDED | 0.000678s
      db.find | STARTED | {"find"=>"authors", "filter"=>{"_id"=>{"$in"=>[BSON::ObjectId('51393dad509f9f4db7000007'), BSON::ObjectId('513945663684a9dbb0000002'), BSON::ObjectId('51c911dc961afd96a9000009'), BSON::ObjectId('5205b3f4cc75585db3000007')]}}}
      db.find | SUCCEEDED | 0.003761s
      

      which tries to load all 4 authors in the seed data, rather than just the one belonging to `highlighted_post`.

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            mmun Martin Muñoz
            Votes:
            1 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: