MongoDB 按小时分组

MongoDB group by hour(MongoDB 按小时分组)
本文介绍了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:

小时 |每小时计算推文

hour | count tweets in hour

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/

您还需要从所使用的任何一种编程语言中找到合适的方式来使用聚合框架.

You will also need to find appropriate way of of using aggregation framework from whichever programming language you are using.

这篇关于MongoDB 按小时分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)