A pipeline stage specification object must contain exactly one field with php mongo aggregate

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I am trying to use aggregate with with project, match and sort but i am getting an exception (MongoResultException to be exact) saying

exception: A pipeline stage specification object must contain exactly one field.

It works fine when I did not use sort and limit but I need them for this. The reason I am not using find() because I read somewhere that it can increase performance. Please help

$query = array(.... //An actual query that works with find() $collection = $this->db->CollectionName;             $project = array(                 '$project'  => array(                     'Field1'    => 1,                     'Field2'=> 1,                     'Field3'=> 1,                     'Field4'      => 1                 )             );             $match = array( '$match'=>$query);             $sort = array('Field3' => -1, 'Field4'=>-1);             $limit = array('$limit' => 100);               $result = $collection->aggregate(array($match,$project,$sort,$limit));             return $result; 

回答1:

It looks like the problem is your $sort assignment. You have

   $sort = array('Field3' => -1, 'Field4'=>-1); 

which doesn't actually give the '$sort' stage specification. Shouldn't it be:

    $sort = array('$sort' => array( 'Field3' => -1, 'Field4'=>-1 ) ); 


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