title: select distinct column count in Aggregation query in mongodb
body: <p><strong>================= Edited for simple problem statement start ================</strong></p>
  
  <pre><code>db.t2.insert({_id:1,account:"abc",vendor:"amazon"});
  db.t2.insert({_id:2,account:"abc",vendor:"overstock"});
  db.t2.insert({_id:3,account:"abc",vendor:"overstock"});
  </code></pre>
  
  <p>Now you have to find out count of unique vendors group by account.
  Here it will show answer is </p>
  
  <pre><code>{ "_id" : "abc", "number" : 2 }
  </code></pre>
  
  <p>Possible solutions are </p>
  
  <pre><code>db.t2.aggregate(
  { $group : { _id : { "z" : "$z", "v" : "$v" }} },
  { $group : { _id : "$_id.z", number : { $sum : 1 } } }
  );
  </code></pre>
  
  <p>Or just add to set and then count it But Assume you have millions records, then how effectively like sql statement you can achieve the same ? </p>
  
  <pre><code>select count(distinct(vendor)) from t group by account
  </code></pre>
  
  <p><strong>=================== Problem statement ends ============================</strong></p>
  
  <p>So i did like following... </p>
  
  <pre><code>db.t.insert({_id:1,v:"xyz",z:1});
  db.t.insert({_id:3,v:"123",z:1});
  db.t.insert({_id:5,v:"xyz",z:1});
  </code></pre>
  
  <p>Now I wants to execute following query </p>
  
  <pre><code>select count(distinct(v)) from t group by z;
  </code></pre>
  
  <p>So the result expected is for z = 1 distinct values are xyz &amp; 123</p>
  
  <pre><code>{ "_id" : 1, "number" : 2 }
  </code></pre>
  
  <p>I can execute following and get the result as above.</p>
  
  <pre><code>db.t.aggregate(
  { $group : { _id : { "z" : "$z", "v" : "$v" } } },
  { $group : { _id : "$_id.z", number : { $sum : 1 } } }
  );
  </code></pre>
  
  <p>But I don't wants to execute the $group twice. Because lets say i have bigger collection, then first it will do group by and whatever intermediate <strong>result will be stored in memory till 2nd group by applies</strong>. Which is exactly what i wants to avoid.</p>