Definition定义
db.collection.countDocuments(query, options)Returns an integer for the number of documents that match the query of the collection or view. This method is available for use in Transactions.返回一个整数,表示与集合或视图的查询匹配的文档数量。此方法可用于事务。
Compatibility兼容性
This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.所有MongoDB Atlas集群都支持此命令。有关Atlas支持所有命令的信息,请参阅不支持的命令。
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Syntax语法
The countDocuments() method has the following form:countDocuments()方法具有以下形式:
db.collection.countDocuments( <query>, <options> )
The countDocuments() method takes the following parameters:countDocuments()方法接受以下参数:
query | ||
options |
The options document can contain the following:options文档可以包含以下内容:
limit | ||
skip | ||
hint | ||
maxTimeMS |
Behavior行为
Mechanics机制
Unlike 与db.collection.count(), db.collection.countDocuments() does not use the metadata to return the count. db.collection.count()不同,db.collection.countDocuments()不使用元数据返回计数。Instead, it performs an aggregation of the document to return an accurate count, even after an unclean shutdown or in the presence of orphaned documents in a sharded cluster.相反,它对文档进行聚合以返回准确的计数,即使在不干净的关闭之后或在分片集群中存在孤立文档的情况下也是如此。
db.collection.countDocuments() wraps the following aggregation operation and returns just the value of 包装以下聚合操作并仅返回n:n的值:
db.collection.aggregate([
{ $match: <query> },
{ $group: { _id: null, n: { $sum: 1 } } }
])Empty or Non-Existing Collections and Views空的或不存在的集合和视图
db.collection.countDocuments() returns 对空的或不存在的集合或视图返回0 on an empty or non-existing collection or view.0。
Query Restrictions查询限制
You cannot use the following query operators as part of the query expression for 您不能将以下查询运算符用作db.collection.countDocuments():db.collection.countDocuments()的查询表达式的一部分:
$where | $expr instead.$expr。 |
$near |
|
$nearSphere |
|
Transactions事务
db.collection.countDocuments() can be used inside distributed transactions.可以在分布式事务中使用。
When you use 在事务中使用db.collection.countDocuments() in a transaction, the resulting count will not filter out any uncommitted multi-document transactions.db.collection.countDocuments()时,生成的计数不会筛选掉任何未提交的多文档事务。
Important
In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design. 在大多数情况下,分布式事务比单文档写入产生更大的性能成本,分布式事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. That is, for many scenarios, modeling your data appropriately will minimize the need for distributed transactions.对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续是数据和用例的最佳选择。也就是说,对于许多场景,适当地对数据进行建模将最大限度地减少对分布式事务的需求。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),另请参阅生产注意事项。
Client Disconnection客户端断开连接
If the client that issued 如果发出db.collection.countDocuments() disconnects before the operation completes, MongoDB marks db.collection.countDocuments() for termination using killOp.db.collection.countDocuments()的客户端在操作完成之前断开连接,MongoDB将使用killOp标记db.collection.countDocuments()以终止。
Examples示例
Count all Documents in a Collection统计集合中的所有文档
To count the number of documents in the 要统计orders collection, use the following operation:orders集合中的文档数量,请使用以下操作:
db.orders.countDocuments( {}, { hint: "_id_"} )
Note
If you use 如果你使用db.collection.countDocuments() with an empty query filter, MongoDB performs a full collection scan which can be inefficient. db.collection.countDocuments()和空查询筛选器,MongoDB会执行完整的集合扫描,这可能效率低下。To improve performance, this example specifies a 为了提高性能,此示例指定了一个hint() to use the automatically generated _id index. hint()来使用自动生成的_id索引。Alternatively, you can use a query filter that finds all documents such as 或者,您可以使用一个查询筛选器来查找所有文档,例如{ "_id": { $gte: MinKey } } to count all documents using an index.{ "_id": { $gte: MinKey } },以使用索引对所有文档进行计数。
Count all Documents that Match a Query统计与查询匹配的所有文档
Count the number of the documents in the 统计orders collection with the field ord_dt greater than new Date('01/01/2012'):orders集合中字段ord_dt大于new Date('01/01/2012')的文档数量:
db.orders.countDocuments( { ord_dt: { $gt: new Date('01/01/2012') } }, { limit: 100 } )