cursor.count()

在本页面

Definition

在 2.6 版中进行了更改:MongoDB 支持将hint()count()结合使用。有关示例,请参见指定要使用的索引

count()方法具有以下原型形式:

db.collection.find(<query>).count()

count()方法具有以下参数:

Parameter Type Description
applySkipLimit boolean 可选的。指定是否在计数中考虑cursor.skip()cursor.limit()方法的效果。默认情况下,count()方法将忽略cursor.skip()cursor.limit()的影响。将applySkipLimit设置为true以考虑这些方法的效果。

MongoDB 还提供了等效的db.collection.count()来替代db.collection.find(<query>).count()构造。

See also

cursor.size()

Behavior

Sharded Clusters

在分片群集上,如果存在orphaned documents或正在进行chunk migration,则count()可能会导致不准确的计数。

为避免这些情况,请在分片群集上使用db.collection.aggregate()方法:

db.collection.aggregate([
   { $count: "myCount" }
])

$count阶段等效于以下$group $project序列:

db.collection.aggregate( [
   { $group: { _id: null, myCount: { $sum: 1 } } },
   { $project: { _id: 0 } }
] )
db.collection.aggregate( [
   { $match: <query condition> },
   { $count: "myCount" }
] )

或者,如果使用等效的$group + $project

db.collection.aggregate( [
   { $match: <query condition> },
   { $group: { _id: null, myCount: { $sum: 1 } } },
   { $project: { _id: 0 } }
] )

See also

$collStats返回基于集合元数据的近似计数。

Index Use

考虑具有以下索引的集合:

{ a: 1, b: 1 }

执行计数时,在以下情况下,MongoDB 可以仅使用索引返回计数:

例如,以下操作可以仅使用索引返回计数:

db.collection.find( { a: 5, b: 5 } ).count()
db.collection.find( { a: { $gt: 5 } } ).count()
db.collection.find( { a: 5, b: { $gt: 10 } } ).count()

但是,如果查询可以使用索引,但是查询谓词不能访问单个连续的索引键范围,或者查询还包含索引之外字段的条件,那么除了使用索引之外,MongoDB 还必须读取文档返回计数。

db.collection.find( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()
db.collection.find( { a: { $gt: 5 }, b: 5 } ).count()
db.collection.find( { a: 5, b: 5, c: 5 } ).count()

在这种情况下,在初次读取文档期间,MongoDB 会将文档分页到内存中,以便后续对相同计数操作的调用将具有更好的性能。

Examples

以下是count()方法的示例。

计算所有文件

以下操作计算orders集合中所有文档的数量:

db.orders.find().count()

计数与查询匹配的文档

以下操作计算orders集合中字段ord_dt大于new Date('01/01/2012')的文档数:

db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()

限制文件数

以下操作计算orders集合中字段ord_dt大于new Date('01/01/2012')的文档数* *考虑到limit(5)的影响:

db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).limit(5).count(true)

指定要使用的索引

以下操作使用名为"status_1"的索引(索引键规范为{ status: 1 })返回orders集合中字段ord_dt大于new Date('01/01/2012')status字段等于"D"的文档计数:

db.orders.find(
   { ord_dt: { $gt: new Date('01/01/2012') }, status: "D" }
).hint( "status_1" ).count()
首页