title: count() is slow operation in MongoDB, how to speed up count() specifically?
body: <p>I have a collection called ParseRequest. It is Shaded with sharing key _id. Probably not the best choice but right now I do not think it matters as the Collection only has 40,000 documents.
  There are two properties on ParseRequest collection that I am concerned with in this case: processed (Boolean)  and parsed (Boolean).</p>
  
  <p>I need to run this query and I want it to be lightning fast: </p>
  
  <p>db. ParseRequest.count({processed: true, parsed: true})</p>
  
  <p>So I tried two different ways:</p>
  
  <ol>
  <li>Have separate composite key on processed and parsed</li>
  <li>Include processed and parsed into shard key</li>
  </ol>
  
  <p>Both ways improve performance but not enough, the count() above runs in 2-3 seconds or so, but I need much faster than that. </p>
  
  <p>What is noteworthy, this query returns in no time (few milliseconds):</p>
  
  <p>db. ParseRequest.find({processed: true, parsed: true}).limit(5)</p>
  
  <p>But </p>
  
  <p>db. ParseRequest.count({processed: true, parsed: true})</p>
  
  <p>is still slow in either setup.</p>
  
  <p>Is there anything else I should try?</p>
  
  <p>Departing from this specific example above, it looks like in general count() for a specific criteria is very expensive operation in MongoDB. Even if you have an index it is still slow to do count; way slower than getting first few rows for the same criteria. Is there any reason for that? </p>
  
  <p>I am coming from SQL Server background: calculating count(*) was always a fast thing in SQL Server. Calculating count is important to my app, and my frustration with MongoDD has grown so much that I am considering dumping MongoDB for that reason alone: slow to calculate count() for a specific criteria. But before I do that I want to be sure that I exhausted all possible ways to improve count calculation. Any suggestion is appreciated. Thank you. </p>
  
  <p>-=-=-</p>
  
  <p>Edit after firts few comments:</p>
  
  <p>I use v2.2.6 running on Centos (64 bit)</p>
  
  <p>Yes, explain says the idex is used and by the way without index it is even slower.</p>
  
  <p>Yes I undestand that to calculate count() for a specific criteria the entire index tree needs to be scanned, but please excuse my comarison to SQL Server, in SQL Server it is also a complete index and yet somehow count(*) is faster everything else being equal. So is there any trick I can use in MongoDB?      </p>