
在使用原生 MongoDB PHP Driver(如 MongoDB\Driver\Query)执行分页查询时,无法直接调用 count() 方法获取总记录数;需通过 toArray() 将游标转为数组后使用 PHP 的 count() 函数统计。
在使用 mongodb\driver\query 时,无法直接调用 `count()` 方法获取总记录数;需通过 `toarray()` 将游标转为数组后使用 php 的 `count()` 函数统计。
当使用 MongoDB 原生 PHP 驱动(即 mongodb/mongodb 的底层驱动 ext-mongodb)进行分页查询时,MongoDB\Driver\Cursor 对象不提供 count() 方法——该方法早在较早版本中已被移除,官方推荐通过聚合管道或单独的计数查询获取总数,而非依赖游标自身。
但需特别注意:$result->toArray() + count($result) 仅返回当前游标中实际返回的文档数量(即 limit 后的数量),而非满足 $conditionArray 的全部匹配记录总数。若你真正需要的是「满足条件的总记录数」(用于分页器显示总页数),则必须额外执行一次独立的计数查询,而非对分页结果数组计数。
✅ 正确做法:分别执行「数据查询」和「总数查询」
// 1. 数据查询(带分页)
$db = mongoConnection('bulk');
$option['projection'] = self::$fields;
$newPage = $page - 1;
$skip = $newPage * $limit;
$option['skip'] = $skip;
$option['limit'] = $limit;
$option['sort'] = ['cpc' => -1];
$option['allowDiskUse'] = true;
$query = new MongoDB\Driver\Query($conditionArray, $option);
$result = $db->executeQuery(env('MONGODBNAME', '') . '.jobs', $query);
$data = iterator_to_array($result); // 或 $result->toArray()
// 2. 总数查询(无 skip/limit,仅 count)
$countQuery = new MongoDB\Driver\Query($conditionArray, ['limit' => 0]); // limit=0 显式忽略限制
$countResult = $db->executeQuery(env('MONGODBNAME', '') . '.jobs', $countQuery);
$totalCount = iterator_count($countResult); // ✅ 安全、内存友好的计数方式(不加载全部文档到内存)⚠️ 注意事项:
- ❌ 避免 count($result->toArray()):会将所有匹配文档加载到内存再计数,严重浪费资源且不可扩展;
- ✅ 推荐 iterator_count($countResult):底层遍历游标而不实例化文档对象,高效低开销;
- ? 若需更高性能或复杂条件(如含 $lookup、$facet),应改用 MongoDB\Driver\Command 执行 count 命令或聚合管道(如 [{ $count: "total" }]);
- ? 确保已启用 allowDiskUse(如需)且 MongoDB 版本 ≥ 4.0(count 命令在 5.0+ 已弃用,推荐聚合 $count)。
总结:MongoDB\Driver\Cursor::count() 已不存在,切勿尝试调用;获取真实总记录数必须发起独立计数查询,并优先使用 iterator_count() 实现轻量级统计。


















