title: How does mongodb $size work?
body: <p>Say I have a collection "posts", and a post can have comments which is stored as an array on a post document, like so:</p>
  
  <pre><code>{
      ...
      comments : [ ... ]
      ...
  }
  </code></pre>
  
  <p>If I want to count the number of comments on a particular post, I can do <code>{ $size : "$comments" }</code>. However, looking at the bson binary format, it does not look like it actually stores the size of the array anywhere, it is just a document with keys 0, 1, 2...</p>
  
  <p>If that is the case, does it have to iterate through all the comments to count them? This seems inefficient, especially if you had a lot of posts with say over 1000 comments.</p>
  
  <p>There is an obvious fix for this. Just store the count on the document.</p>
  
  <pre><code>{
      ...
      commentCount : 23,
      comments : [ ... ]
      ...
  }
  </code></pre>
  
  <p>I am just curious if mongo does something behind the scenes where this is not a problem I should worry about.</p>
  
  <p>Thanks.</p>