title: MongoDB groupby query
body: <p>I have colletions containing records like </p>
  
  <pre><code>{ "type" : "me", "tid" : "1"  }
  { "type" : "me", "tid" : "1" }
  { "type" : "me", "tid" : "1" }
  { "type" : "you", "tid" : "1" }
  { "type" : "you", "tid" : "1" }
  
  { "type" : "me", "tid" : "2" }
  { "type" : "me", "tid" : "2"}
  { "type" : "you", "tid" : "2"}
  { "type" : "you", "tid" : "2" }
  { "type" : "you", "tid" : "2"}
  </code></pre>
  
  <p>I have want result like below</p>
  
  <pre><code>[
   {"tid" : "1","me" : 3,"you": 2},
   {"tid" : "2","me" : 2,"you": 3}
  ]
  </code></pre>
  
  <p>I have tried group  and; aggregate queries doesn't get required result format.</p>
  
  <p>below is the group query.</p>
  
  <pre><code>db.coll.group({
    key: {tid : 1,type:1},
    cond: { tid  : { "$in" : [ "1","2"]}  }, 
    reduce: function (curr,result) { 
      result.total = result.total + 1
    },
    initial: { total : 0}
  })
  </code></pre>
  
  <p>it result is like </p>
  
  <pre><code>[
    {"tid" : "1",  "type" : "me" ,"total": 3 },
    {"tid" : "1","type" : "you" ,"total": 2 },
    {"tid" : "2", "type" : "me" ,"total": 2 },
    {"tid" : "2","type" : "you" ,"total": 3 }
  ]
  </code></pre>
  
  <p>following is aggregate query</p>
  
  <pre><code>db.coll.aggregate([
    {$match : { "tid" : {"$in" : ["1","2"]}}},
    {$group : { _id : {tid : "$tid",type : "$type"},total : {"$sum" : 1}}}
  ])
  </code></pre>
  
  <p>gives following result </p>
  
  <pre><code>{ 
    "result" : 
    [
      {"_id" : {"tid" : "1","type" : "me"},"total" : 3},
      {"_id" : {"tid" : "2","type" : "me" },"total" : 2},
      {"_id" : {"tid" : "2","type" : "you"},"total" : 3}
    ]
    "ok" : 1
  }
  </code></pre>
  
  <p>it is possible to obtain I specified result or I have to do some manipulation in my code.</p>
  
  <p>Thanks</p>