我将推文保存到 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。我想要结果:
小时 |每小时计算推文
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 控制台上使用聚合框架进行分组
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/
您还需要从所使用的任何一种编程语言中找到合适的方式来使用聚合框架。
关于javascript - MongoDB 按小时分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23293082/