title: Understanding performance: mongo aggregation vs count
body: <p>If I do a count query, I get the results in &lt;2seconds</p>
  
  <pre><code>db.coll.find({"A":1,"createDate":{"$gt":new Date("2011-05-21"),"$lt":new Date("2013-08-21")}}).count()
  </code></pre>
  
  <p>This uses the following index</p>
  
  <pre><code>db.coll.ensureIndex({"A":1,"createDate":1})
  </code></pre>
  
  <p>Similarly, there are 4 columns A,B,C,D(values are always 0 or 1) for which I run 4 count queries and get results in &lt;10seconds.</p>
  
  <p>I looked at the aggregation framework documentation and created an aggregated query to do all 4 sums together.</p>
  
  <pre><code>db.coll.aggregate(  { $match : {"createDate":{$gt:new Date("2013-05-21"),$lt:new Date("2013-08-21")} } },
  { $group :
                           { _id:null,
                           totalA : { $sum : "$A" },
                           totalB : {$sum: "$B},
                           totalC:{$sum: "$C"},
                           totalD:{$sum: "$D"}}} 
   ) 
  </code></pre>
  
  <p>I also created an index:</p>
  
  <pre><code>db.coll..ensureIndex({"createDate":1,"A":1,"B":1,"C":1,"D":1})
  </code></pre>
  
  <p>According to the documentation, this index covers my aggregate function. But the return of the aggregate is in ~18seconds. </p>
  
  <p>I'm confused here. Is there anything basic which I missed or is there any fundamental concept lying behind which makes aggregation slower than count.
  I am also concerned about the overhead due to number of queries to be fired from mongo from the code for fetching count.</p>