MongoDB\Collection::countDocuments()
新增自版本1.4.
定义
参数
返回值
匹配过滤器条件的文档数量。
错误/异常
MongoDB\Exception\UnexpectedValueException
如果服务器命令响应格式不正确。
MongoDB\Exception\UnsupportedException
如果使用了选定的服务器不支持选项(例如 collation
、readConcern
、writeConcern
)。
MongoDB\Exception\InvalidArgumentException
与参数或选项解析相关的错误。
MongoDB\Driver\Exception\RuntimeException 用于其他扩展级别的错误(例如连接错误)。
行为
内部,此方法使用 $group
聚合管道操作符来获取结果。如果给出了 filter
参数,则将其转换为 $match
管道操作符。如果选项中存在,将在 $match
和 group
之间添加可选的 $skip
和 $limit
阶段。
注意
此方法在服务器端计算文档数量。要获取没有筛选条件的文档的近似总数,可以使用 MongoDB\Collection::estimatedDocumentCount()
方法。此方法根据集合元数据估计文档数量,从而在性能上牺牲了准确性。
由于此方法使用聚合管道,因此在 MongoDB\Collection::count()
filter
中接受的某些查询操作符无法使用。考虑以下替代这些受限操作符的方法
When evaluating query criteria, MongoDB compares types and values according to its own comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class in the extension (e.g. use MongoDB\BSON\ObjectId to match an ObjectId).