title: What is the efficient way of counting 2 level nested model (using mongoid or MongoDB in general)?
body: <p>I have following data models. In which a Project embeds many ComponentDescriptor, and a ComponentDescriptor embeds many Statistic. </p>
  
  <pre><code>class Project
    include Mongoid::Document
    embeds_many :component_descriptors
  
    field :status, :type =&gt; Integer
  
    backgrounded :publish 
  end
  
  class ComponentDescriptor
    include Mongoid::Document
    include Mongoid::Acts::Tree
  
    embeds_many :statistics
    embedded_in :project, :inverse_of =&gt; :component_descriptors
  
  end
  
  
  class Statistic
    include Mongoid::Document
    field :statistics_type, :type =&gt; String
    field :data, :type =&gt; String
    field :playhead_time, :type =&gt; String
    field :remote_ip, :type =&gt; String
    field :user_agent, :type =&gt; String
  
    embedded_in :component_descriptor, :inverse_of =&gt; :statistics
  end
  </code></pre>
  
  <p>The question is what is the best way to count the total number of Statistic object in a Project. </p>
  
  <p>One way I can think of is looping through each ComponentDescriptor and count the number of Statistics objects and then sum them up. But I think this is not efficient way. </p>
  
  <p>Thank in advance.</p>