title: How to find a document with array size within a range in MongoDB?
body: <p>Given the following document structure:</p>
  
  <pre><code>{
    _id : Mongo ID,
    data : [someData1, someData2, ..., someDataN]
  }
  </code></pre>
  
  <p>I want to get all documents which <code>data</code> size is between <code>a</code> and <code>b</code> (strict positive integers, consider <code>a &lt; b</code> is always true).<br>
  I first thought about using <a href="http://docs.mongodb.org/manual/reference/operator/query/size/#op._S_size" rel="nofollow noreferrer"><code>$size</code></a>, but the Mongo doc states:</p>
  
  <blockquote>
    <p><code>$size</code> does not accept ranges of values. To select documents based on fields with different numbers of elements, create a <strong>counter field</strong> that you increment when you add elements to a field.</p>
  </blockquote>
  
  <p><em>(Emphasis mine)</em></p>
  
  <p>How to retrieve all the documents with a <code>data</code> array of length between <code>a</code> and <code>b</code> without using a counter?</p>
  
  <hr>
  
  <p>Related but did not solve:</p>
  
  <ul>
  <li>This <a href="https://stackoverflow.com/questions/10870354/query-returning-count-of-items-in-mongodb-embedded-collection/10874002#10874002">answer</a> which suggests using a counter</li>
  <li>This <a href="https://stackoverflow.com/questions/6722850/querying-internal-array-size-in-mongodb">question</a> which asks how to query an internal length
  and got many answers</li>
  <li>This <a href="https://stackoverflow.com/questions/19221784/mongodb-select-all-entries-where-inner-data-count-is-greater-then-zero/19222054#19222054">answer</a> which suggests to use: <code>{ 'data.' + b : { $exists : true } }</code> but I don't know how reliable it is and how it could apply to a range</li>
  <li>This <a href="https://stackoverflow.com/questions/7811163/in-mongodb-how-do-i-find-documents-where-array-size-is-greater-than-1">question</a> about how to find documents with a minimal array length</li>
  </ul>