title: count multiple distinct fields by group with Mongo
body: <p>I have a data set looks as </p>
  
  <pre><code>{"BrandId":"a","SessionId":100,"UserName":"tom"}
  {"BrandId":"a","SessionId":200,"UserName":"tom"}
  {"BrandId":"b","SessionId":300,"UserName":"mike"}
  </code></pre>
  
  <p>I would like to count distinct session and username group by brandid, the sample sql is like:</p>
  
  <pre><code>select brandid,count_distinct(sessionid),count_distinct(username)
  from data
  group by brandid
  </code></pre>
  
  <p>I tried to write Mongo DB, my current code is as following and it does not work. Is there anyway to make it work?</p>
  
  <pre><code>db.logs.aggregate([ 
      {$group:{
          _id:{brand:"$BrandId",user:"$UserName",session:"$SessionId"},  
          count:{$sum:1}}}, 
      {$group:{
          _id:"$_id.brand",
          users:{$sum:"$_id.user"},
          sessions:{$sum:"$_id.session"}
      }}
  ])
  </code></pre>
  
  <p>for the certain example, the expected count is </p>
  
  <pre><code>{"BrandId:"a","countSession":2,"countUser":1}
  {"BrandId:"b","countSession":1,"countUser":1}
  </code></pre>
  
  <p>if you know SQL, the expect result is as same as the SQL I mentioned.</p>