我想将 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)) #
您可以使用聚合管道执行以下操作:
datetime
字段转换为时间戳(由 $subtract
1970-01-01)datetime
(by '$add' 1970-01-01)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供您参考。