user1645542
user1645542

Reputation: 43

mongodb aggregation framework groupby multiple fields

My collection is like

{queid:'1',date:'07023/2013',topic: 'topic1'}
{queid:'2',date:'07022/2013',topic: 'topic2'}
{queid:'3',date:'07022/2013',topic: 'topic1'}
{queid:'4',date:'07023/2013',topic: 'topic1'}

i want my output to be like

{topic1:
    [ {date:'07/23/2013',count:2},
      {date:'07/22/2013',count:1}
    ]
}

is this possible to do it mongodb..

I tried doing this

que.aggregate([{$match:c},{$group:{_id:'$topic',count:{$push:'$date'}}}])

which gives output as

{
        "_id" : "topic",
        "count" : [
                "2013-06-04",
                "2013-06-06",
                "2013-06-17",
                "2013-06-20"
] }

i am nt able to understand how to group in the array and populate counts.

Upvotes: 0

Views: 99

Answers (2)

Ryan Wong
Ryan Wong

Reputation: 120

the Map-Reduce may suit for you.

eg:

map = function (){
  emit(this.topic+this.date, 1);
}

reduce = function (id, vals){
  return Array.sum(vals);
}

db.coll.mapReduce(map, reduce, {out:'results'});

http://docs.mongodb.org/manual/tutorial/map-reduce-examples/

Upvotes: -1

Yevgeniy Anfilofyev
Yevgeniy Anfilofyev

Reputation: 4847

I don't know what does mean {$match:c} in your code. Actually, I'm a newbie in mongodb, and this code:

que.aggregate([
  {$group:{_id:{"topic":"$topic","date":"$date"}, sum:{$sum:1}}},
  {$group:{_id:"$_id.topic", "dates":{$push:{"date":"$_id.date", "count":"$sum"}} }}
])

produces:

{
  "result" : [
     {
      "_id" : "topic2",
      "dates" : [
        { "date" : "07022/2013", "count" : 1}
      ]
     },
     {
      "_id" : "topic1",
      "dates" : [
        { "date" : "07022/2013", "count" : 1},
        { "date" : "07023/2013", "count" : 2}
      ]
     }
  ],
  "ok" : 1
}

I think you can play with it to get what do you want.

Upvotes: 1

Related Questions