使用 PHP 在 MongoDb 中按 15 分钟时间间隔对结果进行分组

问题描述 投票:0回答:1

我想将 MYSQL 查询转换为 MongoDB PHP 查询我已经尝试过但不起作用。

SELECT time,ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8 FROM logs WHERE date_time >= '2021-07-05T12:12:48.000Z' AND date_time<= '2021-07-05T13:12:48.000Z' GROUP BY date_time(25m) fill(0) tz('Asia/Kolkata')

我已经在 mongo PHP 中进行了转换,但出现错误。

     $results = $this->dbs->$collection_name->aggregate(array(
            array(      
                '$match' => array(
                    'date_time' => array
                    (
                        '$gte' => $from_date, '$lte' => $to_date
                    )
                )
            ),
            array(
                '$group' => array(
                   '_id' => array(
                        '$toDate' => array(
                            '$subtract' => array(
                                array('$toLong'=> array('$toDate'=> '$_id')),
                                array('$mod'=> array('$toLong'=> array('$toDate'=> '$_id'),1000 * 60 * 15) )
                            )
                        )
                    ),
                )
            )
        ));

错误:这个错误来了:致命错误:未捕获 MongoDB\Driver\Exception\CommandException:表示一个对象 表达式必须只有一个字段: { $toLong: { $toDate: "$_id" }, 0: 900000 } 中 F:\xamp\htdocs\logger endor\mongodb\mongodb\src\Operation\Aggregate.php:298 堆栈跟踪:#0 F:\xamp\htdocs\logger endor\mongodb\mongodb\src\Operation\Aggregate.php(298): MongoDB\Driver\Server->executeReadCommand('clients_logers', 对象(MongoDB\驱动程序\命令),数组)#1 F:\xamp\htdocs\logger endor\mongodb\mongodb\src\Collection.php(258): MongoDB\Operation\Aggregate->execute(Object(MongoDB\Driver\Server)) #

php arrays mongodb mongodb-query aggregation-framework
1个回答
0
投票

您可以使用聚合管道执行以下操作:

  1. datetime
    字段转换为时间戳(由
    $subtract
    1970-01-01)
  2. 对时间戳字段进行整数除以 15 分钟 = 15 * 60 * 1000 = 900000 ms
  3. 将结果乘以 900000ms
  4. 转换回
    datetime
    (by '$add' 1970-01-01)
  5. 按15分钟分组结果分组
db.collection.aggregate([
  {
    "$addFields": {
      "datetime": {
        "$add": [
          ISODate("1970-01-01"),
          {
            "$multiply": [
              {
                $floor: {
                  "$divide": [
                    {
                      $subtract: [
                        "$datetime",
                        new Date("1970-01-01")
                      ]
                    },
                    900000
                  ]
                }
              },
              900000
            ]
          }
        ]
      }
    }
  },
  {
    $group: {
      _id: "$datetime",
      cnt: {
        $sum: 1
      }
    }
  }
])

这里是Mongo Playground供您参考。

© www.soinside.com 2019 - 2024. All rights reserved.