MongoDB watch group

I save tweets in 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) {});
    });
});

Everything is fine.

The tweet time in MongoDB is in the format: 2014-04-25 11:45:14 GMT (column created_at) Now I need a group column created_at in hours. I would like to get the result:

hour | count tweets per hour


1 | 28

2 | 26

3 | 32

4 | 42

5 | 36

...

My unsuccessful attempt:

    $keys = array('created_at' => true);
    $initial = array('count' => 0);
    $reduce = "function(doc, prev) { prev.count += 1 }";

    $tweetsGroup = $this->collectionAnimal->group( $keys, $initial, $reduce );

But I do not have the ability to group by hour.

How to do it?

+4
source share
2 answers

I can tell you how you can group the aggregation structure directly on the 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"}
   }
 })

You can see additional parameters here: http://docs.mongodb.org/manual/reference/operator/aggregation-date/

.

+10

$project $group _id. , :

, { "$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 , , . , , .

+4

Source: https://habr.com/ru/post/1538062/


All Articles