MongoDB按小时分组
我将推文保存到mongo DB:
I save tweets to mongo DB:
twit.stream('statuses/filter', {'track': ['animal']}, function(stream) {
stream.on('data', function(data) {
console.log(util.inspect(data));
data.created_at = new Date(data.created_at);
collectionAnimal.insert(data, function(err, docs) {});
});
});
没关系。
推文时间在MongoDB格式为:2014-04-25 11:45:14 GMT(column created_at)
现在我需要小时创建组列created_at。我想得到结果:
The tweet time in MongoDB is in format: 2014-04-25 11:45:14 GMT (column created_at) Now I need group column created_at in hours. I would like to have the result:
小时|以小时计数推文
1 | 28
2 | 26
3 | 32
4 | 42
5 | 36
...
我未成功的尝试:
$keys = array('created_at' => true);
$initial = array('count' => 0);
$reduce = "function(doc, prev) { prev.count += 1 }";
$tweetsGroup = $this->collectionAnimal->group( $keys, $initial, $reduce );
但我无法按小时分组。
怎么做?
我可以告诉你如何在mongo控制台上直接使用聚合框架进行分组
I could tell you how you can group using aggregation framework directly on mongo console
db.tweets.aggregate(
{ "$project": {
"y":{"$year":"$created_at"},
"m":{"$month":"$created_at"},
"d":{"$dayOfMonth":"$created_at"},
"h":{"$hour":"$created_at"},
"tweet":1 }
},
{ "$group":{
"_id": { "year":"$y","month":"$m","day":"$d","hour":"$h"},
"total":{ "$sum": "$tweet"}
}
})
有关更多选项,请参阅此处: http://docs.mongodb.org / manual / reference / operator / aggregation-date /
For more options you can look here: http://docs.mongodb.org/manual/reference/operator/aggregation-date/
您还需要找到使用whi聚合框架的适当方法你正在使用的chever编程语言。
You will also need to find appropriate way of of using aggregation framework from whichever programming language you are using.