MongoDB按小时分组

MongoDB group by hour

本文关键字:小时 MongoDB      更新时间:2023-09-26

我将tweets保存到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(列created_at)现在我需要以小时为单位创建组列created_at。我想要结果:

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控制台上直接使用聚合框架进行分组

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/

您还需要从您使用的任何编程语言中找到使用聚合框架的适当方式。

此处不需要使用$project阶段,因为在定义分组_id时,日期运算符函数可以直接在$group步骤中使用。这样就省去了为了得到结果而处理整个收集的麻烦:

此外,您只是在计算,所以简单地说{ "$sum" : 1 },其中定义一个不存在的字段是导致0的问题。

    $this->collection->aggregate(array(
        array(
            '$group' => array(
                "_id" => array( 
                    "y" => array( '$year' => '$created_at' ),
                    "m" => array( '$month' => '$created_at' ),
                    "d" => array( '$dayOfMonth' => '$created_at' ),
                    "h" => array( '$hour' => '$created_at' ),
                ),
                "total" => array( '$sum' => 1 ),
            ),
        )
    ));

如果有任何内容,请在管道开始处添加$match阶段,以便筛选日期。如果一天的输出是可以接受的,那么您只需要在分组中定义$hour,并且您正在减少工作集的大小,这意味着更快。也许还有你无论如何都想做的事。

Lalit的答案对我不起作用,它一直给我零。相反,我做了:

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"},
       'count':{$sum:1} 
   }
 })

CCD_ 7是唯一的区别。

可能会帮助像我这样的mongo新手。

自MongoDB 5.0(2021年)以来,您可以使用$dateTruncunit: 'hour'参数:

db.tweets.aggregate([
  {
    $project: {
      hour: { $dateTrunc: { date: "$created_at", unit: "hour" } },
    },
  },
  {
    $group: {
      _id: "$hour",
      count: { $sum: 1 },
    },
  },
])