How to subtract in mongodb php

岁酱吖の 提交于 2019-12-13 01:16:54

问题


 $getdataPipeline = array(
            array(
                '$match' => array(
                    'project_id' => array('$in' => $mysql_project_id) // Validating project ID
                ),
                '$match' => array('project_id' => $project_id)
            ),
            array(
                '$group' => array(
                    '_id' => array('pro_id' => '$project_id', 'uid' => '$user_id'),
                    "wh" => array('$subtract' => array(array('$sum' => '$toltal_timein_minutes'), array('$sum' => '$holding_durationin_minutes')))

                ))
        );

Running query:

  $ValidProjectIdInMongo = $collection->aggregate($getdataPipeline);

I'm getting an error like

Uncaught exception 'MongoResultException' with message 'localhost:27017: exception: unknown group operator '$subtract''


回答1:


The $sum is the accumulator to be used with $group, so it must be the top level operator used. Therefore your other operations need to happen "inside" the $sum:

$getdataPipeline = array(
    array(
        '$match' => array('project_id' => $project_id)
    ),
    array(
        '$group' => array(
            '_id' => array('pro_id' => '$project_id', 'uid' => '$user_id'),
            "wh" => array( 
                '$sum' => array( 
                    '$subtract' => array( 
                        '$toltal_timein_minutes', 
                        '$holding_durationin_minutes'
                    ) 
                ) 
            )
        )
    )
);

You can do it here because this is basic subtraction, but more complex operations would generally require a separate $project stage after the $group.

Also note that yout $match pipeline stage is incorrect and will actually be interpretted just as I have re-written above. You perhaps mean in $in condition for both the possible values, which is a logical $or.

You also have what looks like typing errors in the field names.



来源:https://stackoverflow.com/questions/32710113/how-to-subtract-in-mongodb-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!