title: MongoDB: aggregation group by a field in large collection
body: <p>I have a large (millions) collection of files where tags is an array field like this.</p>
  
  <pre><code>{
      "volume" : "abc", 
      "name" : "file1.txt", 
      "type" : "txt", 
      "tags" : [ "Interesting", "Weird" ], ...many other fields
  }
  </code></pre>
  
  <p>Now I want to return count of unique tags for the entire collection. I am using <code>aggregate</code> for that. Here's my query. </p>
  
  <pre><code>db.files.aggregate(
      { "$match" : {"volume":"abc"}},
      { "$project" : { "tags" : 1}},
      { "$unwind" : "$tags"},
      { "$group" : { "_id" : "$tags" , "count" : { "$sum" : 1}}},
      { "$sort" : { "count" : 1}}
  )
  </code></pre>
  
  <p>I am seeing that it takes around 3 seconds for this to return for a collection of 1.2M files. I do have index on <code>tags</code> and <code>volume</code> fields.</p>
  
  <p>I am using MongoDB 2.4. Since 2.6 is not out, I cannot use the <code>.explain()</code> here. </p>
  
  <p>Any ideas how I can improve this performance? I do need to have a summary count. Also, I cannot pre-compute these counts as my <code>$match</code> will be variable based on volume, type, a particular tag, some date time of file etc. </p>