You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:45:25