我正在使用MongoChef
来构建一个聚合管道命令,该命令执行$match
,然后是$group
,然后是$project
。
以下代码生成正确的输出,并确认在MongoDB中工作:
db.collection_name.aggregate(
[
{
$match: {
":energy_mon_id" : 9
}
},
{
$group: {
"_id" : {
"Date" : "$:date"
},
"avg_voltage_a" : {
"$avg" : "$:voltage_a"
},
"avg_voltage_b" : {
"$avg" : "$:voltage_b"
},
"avg_voltage_c" : {
"$avg" : "$:voltage_c"
}
}
},
{
$project: {
"avg_volt" : {
"$add" : [
"$avg_voltage_a",
"$avg_voltage_b"
]
}
}
},
{
$match: {
}
}
]
);
生成的输出是这样的(请注意avg_volt values are integers
):
{ "_id" : { "Date" : "2016-06-06" }, "avg_volt" : 779 }
{ "_id" : { "Date" : "2016-06-08" }, "avg_volt" : 779 }
现在我面临的问题是让它在PHP中正确运行。
PHP中的代码如下:
$collection = $this->db->testdb->collection_name;
$aggrCommand = array(
array(
'$match' => array( ":energy_mon_id" => 9)
),
array(
'$group' => array(
"_id" => array(
"Date" => "$:date"
),
"avg_voltage_a" => array(
'$avg' => "$:voltage_a"
),
"avg_voltage_b" => array(
'$avg' => "$:voltage_b"
),
"avg_voltage_c" => array(
'$avg' => "$:voltage_c"
),
)
),
array(
'$project' => array(
"avg_volt" => array(
'$add' => ["$avg_voltage_a","$avg_voltage_b" ]
)
)
)
);
$list = $collection->aggregate( $aggrCommand);
当我尝试通过邮递员提交GET请求时,我得到的错误是最后一行:
Slim Application Error
The application could not run because of the following error:
Details
Type: MongoDB\Driver\Exception\RuntimeException
Code: 16554
Message: $add only supports numeric or date types, not String
File: C:\wamp\www\DRM\vendor\mongodb\mongodb\src\Operation\Aggregate.php
Line: 168
这完全没有意义,因为MongoDB中的输出是一个整数值,我在转换到PHP时无法发现任何错误。
有一点需要注意的是,我的字段名称确实在前面包含冒号(这不是错误),但我不认为这是问题。
我真的很难过,有人可以就如何解决这个问题提供任何建议吗?我的MongoDB命令的输出显然不是字符串,但在PHP中它表示avg_voltage_a和avg_voltage_b的值是字符串。这毫无意义。
答案 0 :(得分:-2)
尝试使用" $ add"中的单引号防止PHP解释的声明" $ avg_voltage_a"作为变量:
'$add' => ['$avg_voltage_a','$avg_voltage_b' ]