PHP操作MongoDB报错:调用未定义方法MongoDB\Driver\Cursor::limit()
PHP MongoDB 查询报错:Call to undefined method MongoDB\Driver\Cursor::limit()
环境与问题重现
使用环境:MongoDB v4.2、PHP 7.4、Composer 2.5.1,已引入Composer自动加载器并安装MongoDB扩展。
原查询代码:
$all_items = $collection ->find( $where_search, array('_id', 'name', 'email', 'bod', 'mobile') ) ->limit( $per_page ) ->skip( $start ) ->sort( array( $Allele => $sort == 'ASC' ? 1 : -1 ));
执行后报错:
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Cursor::limit() in /var/www/
问题原因
PHP的MongoDB扩展中,find()方法返回的MongoDB\Driver\Cursor对象不支持limit()、skip()、sort()这类链式调用方法。你错误地将查询选项以链式方法的形式调用,正确做法是把这些参数统一传入find()方法的第二个参数(选项数组)中。
修正后的代码
$options = [ 'projection' => ['_id', 'name', 'email', 'bod', 'mobile'], 'limit' => $per_page, 'skip' => $start, 'sort' => [ $Allele => $sort == 'ASC' ? 1 : -1 ] ]; $all_items = $collection->find($where_search, $options);
补充说明
确保你的$collection是MongoDB\Collection类的实例(由Composer安装的mongodb/mongodb库提供),如果直接使用底层MongoDB\Driver相关类,同样需要遵循该规则——所有查询选项都要作为find()的第二个参数传入,而非链式调用方法。
内容的提问来源于stack exchange,提问作者Sam.
相关产品推荐
相关产品推荐

