如何将mongoDB查询转换为PHP?

时间:2016-07-22 11:01:52

标签: php mongodb mongodb-query

我的查询正在使用mongodb并正确生成输出。但同样的查询我试图使用PHP运行然后它给出以下错误

Array
    (
        [ok] => 0
        [errmsg] => A pipeline stage specification object must contain exactly one field.
        [code] => 16435
    )

以下是我的MongoDB查询

db.sample_coll.aggregate(
{
  $unwind: {
        path:"$KeyValues", 
        includeArrayIndex:"arrayIndex", 
        preserveNullAndEmptyArrays:true 
    }
},
{
  $project: {
        timestamp:{ 
          "$add":["$EventTS",{"$multiply":[60000,"$arrayIndex"]}] 
        } ,
        "InputVolt":"$KeyValues.InputVolt", 
        arrayIndex:1
        }
},
{
  $match: {
    $and: [ 
        {InputVolt: {$ne: null}}
    ]
  }
}
); 

以上查询在php中转换

$pipeline = array(
            array('$unwind' => 
                    array( 'path' => '$KeyValues'),
                    array( 'includeArrayIndex' => 'arrayIndex' ), 
                    array( 'preserveNullAndEmptyArrays' => 'true' )
            ),
            array(
                '$project' => array(
                    'timestamp' => array(
                        '$add' => array(
                            '$EventTS',
                            array('$multiply' => array( 60000, '$arrayIndex' )) 
                        )
                    ),
                    array( 'InputVolt' => array( '$KeyValues', 'InputVolt'   ) ) ,
                    array('arrayIndex' => 1)
                )
            ),
            array(
                '$match' => array(
                    '$and' => array(
                        array('InputVolt' => array('$ne' => null )),
                    )
                )
            )

);
$result = $collection->aggregate($pipeline);

请帮助解决此问题。 提前致谢

1 个答案:

答案 0 :(得分:1)

PHP中的管道:

$pipeline = array(
        array('$unwind' => array(
            'path' => '$KeyValues',
            'includeArrayIndex' => 'arrayIndex',
            'preserveNullAndEmptyArrays' => true
        )),
        array('$project' => array(
            'timestamp' => array(
                '$add' => array('$EventTS', array('$multiply' => array(60000, '$arrayIndex')))
            ),
            'InputVolt' => '$KeyValues.InputVolt',
            'arrayIndex' => 1
        )),
        array('$match' => array(
            'InputVolt' => array('$ne' => null)
        ))
    );