Mongodb gets average over time period in PHP in PHP

I play with MongoDB, and although I have seen posts on the Internet about issues like mine, I cannot figure out how to do this.

I have quite a few documents in my collection that contain sensor measurement data as follows:

{
      'timestamp' => new MongoDate(1503119239, 0),
      'sensor_id' => new MongoInt64(4),
      'value' => 12345
}

Unless, of course, the timestamp, sensor_id and value are different for each record.

Using PHP, I want to get the average values โ€‹โ€‹of the PER sensor PER day / month / hour. For example, I tried to get the average value per day using

$pipeline = array(
    array(
        '$group' => array(
            '_id'      => ['sensor_id'=> '$sensor', '$dayOfYear'=>'$timestamp'],
            'avgValue' => array( '$avg' => '$value' ),
        ),
    ),
);

$out = $logdataCollection->aggregate( $pipeline );

I expect it to give me a result like

[0] => ['sensor_id' => '1', 'dayOfYear'=>12, 'avgValue'=>1.123],
[1] => ['sensor_id' => '1', 'dayOfYear'=>13, 'avgValue'=>0.15],
[2] => ['sensor_id' => '2', 'dayOfYear'=>12, 'avgValue'=>1.123],
[3] => ['sensor_id' => '3', 'dayOfYear'=>15, 'avgValue'=>1.123],

and etc.

This example shows the average value by day (during the year), but I want to be able to do this per hour also during the month:

[0] => ['sensor_id' => '1', 'date'=>2015-01-01, 'avgValue'=>1.123],
[1] => ['sensor_id' => '1', 'date'=>2015-01-02, 'avgValue'=>0.15],
[2] => ['sensor_id' => '2', 'date'=>2015-01-01, 'avgValue'=>1.123],
[3] => ['sensor_id' => '3', 'date'=>2015-01-02, 'avgValue'=>1.123],

and etc.

, , , MongoDateTime, , . .

Aggregration, SO - PHP, , . , !

+4
1

, , . :

 $pipeline = array(
    array(
        '$group' => array(
            '_id'      => ['foundDate'=>['$dateToString'=>['format'=>'%Y-%m-%d', 'date'=>'$timestamp']], 'sensor'=>'$sensor'],
            'avgValue' => array( '$avg' => '$value' ),
        ),
    ),
);

, . , :

[0]=>
    array(2) {
      ["_id"]=>
      array(2) {
        ["foundDate"]=>
        string(10) "2016-03-23"
        ["sensor"]=>
        int(2)
      }
      ["avgValue"]=>
      float(526.622580645)
    }
    [1]=>
    array(2) {
      ["_id"]=>
      array(2) {
        ["foundDate"]=>
        string(10) "2016-03-23"
        ["sensor"]=>
        int(3)
      }
      ["avgValue"]=>
      float(480.773846154)
    }
   ...
+2

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


All Articles