title: Extremely slow performance of some MongoDB queries
body: <p>I have a collection of about 30K item all of which have an element called Program. "Program" is a first part of a compound index, so looking up an item with specific Program value is very fast. It is also fast to run range queries, e.g.:</p>
  
  <pre><code>db.MyCollection.find(
  { $and: [ { Program: { "$gte" : "K", "$lt" : "L" } }, 
  { Program: { "$gte" : "X", "$lt" : "Y" } } ] }).count();
  </code></pre>
  
  <p>The query above does not return any results because I am querying for an overlap of two non-overlaping ranges (K-L) and (X-Y)). The left range (K-L) contains about 7K items.</p>
  
  <p>However if I replace the second "and" clause with "where" expression, the query execution takes ages:</p>
  
  <pre><code>db.MyCollection.find(
  { $and: [ { Program: { "$gte" : "K", "$lt" : "L" } }, { "$where" : "this.Program == \"Z\"" } ] }).count();
  </code></pre>
  
  <p>As you can see, the query above should also return an empty result set (range K-L is combined with Program=="Z"). I am aware of slow performance of "where", but should not Mongo first reduce potential result set by evaluating the left clause (that would result in about 7K items) and only then apply "where" check? If it does, should not processing of a few thousand items take seconds and not minutes as it does on my machine with Mongo service consuming about 3GB RAM while peforming this operation? Looks too heavy for relatively small collection.</p>