0

我的收藏就像

{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'}

我希望我的输出像

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

这可以做到吗mongodb ..

我试着这样做

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

输出为

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

我无法理解如何在数组中分组并填充计数。

4

2 回答 2

1

我不知道{$match:c}你的代码是什么意思。实际上,我是 mongodb 的新手,这段代码:

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

产生:

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

我认为你可以玩它来得到你想要的。

于 2013-07-24T07:30:38.337 回答
-1

Map-Reduce 可能适合您。

例如:

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/

于 2013-07-24T05:17:16.747 回答