title: Queries on embedded documents with Mongoid/MongoDB (Rails)
body: <p>I'm trying to figure out what the performance is with Mongoid when doing queries on embedded documents. I'm quite new to Mongoid and MongoDB, so if you spot anything that you think is bad practice, please let me know. </p>
  
  <p>A use case:</p>
  
  <p>Suppose I have a 'post' with many embedded comments in it. The comments are threaded, and each threaded comment has a parent_id field, specifying the parent comment they belong to. Example of a 'post' document:</p>
  
  <pre><code>{ 
    "_id": 1, "username": "Foo", "body": "Hi!", 
    "comments": [ 
                  {"_id": 123, "body": "&lt;3"}, 
                  {"_id": 124, "body": "&lt;/3", "parent_id": "123"}, 
                  ... 
                ]
  }
  </code></pre>
  
  <p>Now suppose a post has a huge amount of comments. When I save a new comment, I want to determine with how many comments the new comment shares its parent. So I do this:</p>
  
  <pre><code>class Comment
    include Mongoid::Document
    field :body
    field :parent_id
    embedded_in :post, :inverse_of =&gt; :comments
  
    before_save :determine_amount
    def determine_amount
      return if self.parent_id.blank?
      amount = self.node.comment.where(:parent_id =&gt; self.parent_id).count
  
      # Do something with it...
    end
  end
  </code></pre>
  
  <p>I'm wondering where and how Mongoid does this query, and how efficient this query is. As far as I know, the query doesn't hit the database, which makes sense because the Topic document is already loaded, and the comments are a subdocument of that.</p>
  
  <p>Would anyone be so kind as to give me directions on how Mongoid handles these cases?</p>