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

Feature request: eliminate n+1 queries when using belongs_to (many) from embedded object

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

      First, I understand that from the point of view of current mongoid errors, I'm doing it wrong. However it's the best solution to the task I have and the problem described here looks easy to fix.

      Problem description.
      I have three classes.

      class USA
        include Mongoid::Document
        embeds_many :states
      end
      
      class State
        include Mongoid::Document
        embedded_in :USA
        belongs_to :person
      end
      
      class Person
        include Mongoid::Document
        has_many :states
      end
      

      So, I can get USA, I can get states in USA. But when I do something along the line of:

      USA.states.each do |state|
        state.person
      end
      

      I'm getting N queries. Instead I'd like to see the next happening query wise.
      Solution:

      Person.where( :_id => {:$in => USA.states.map{|state| state.person_id} })
      

      Some mangling will be necessary to map those objects to their related embedded objects, though.

      While on the topic I'd like to illustrate that it's possible to use this relation to find all the states that belong to the person, even though Mongoid will throw an error.

      class Person
        include Mongoid::Document
        has_many :states
        def self.states
          USA.where('states.person_id' => self._id).map{|usa| usa.states.map{|state| state if state.info_card_id == self._id} }.flatten.compact
        end
      end
      

      As it goes, having embedded object referencing other objects may arise and such methods are pretty straightforward to generate on the fly. In my case I need states in my USA class for fast searching, indexing and retrieval while storing references to other classes. And sometimes I need to know states that are related to particular person.

            Assignee:
            Unassigned Unassigned
            Reporter:
            Slotos Slotos [X]
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: