OPTIONS
翻译或纠错本页面

cursor.count()

说明

cursor.count()

返回游标引用的文档记录数。在 find() 方法后追加 count() 方法来查询匹配的文档记录数。这个操作并没有执行完整的查询,它只取得本次查询可以返回的结果的数量。

在 2.6 版更改: MongoDB 支持 hint() 方法和 count() 方法联合使用。参见 指定使用的索引 中的例子。

The count() method has the following prototype form:

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

The count() method has the following parameter:

Parameter Type Description
applySkipLimit Boolean Optional. Specifies whether to consider the effects of the cursor.skip() and cursor.limit() methods in the count. By default, the count() method ignores the effects of the cursor.skip() and cursor.limit(). Set applySkipLimit to true to consider the effect of these methods.

MongoDB 提供了与 db.collection.count() 方法效果相同的 db.collection.find(<query>).count() 方法,可以任选一个使用。

参见

cursor.size()

行为

分片集群

在分片集群中, |计数操作| 如果存在孤立的文档记录( orphaned documents )或分片移动 ( chunk migration )进程正在运行,会返回一个 错误的 数值。

为了避免这些情况,在分片集群中,可以使用聚合函数( db.collection.aggregate() )中的 $group 操作符对集合执行求和( $sum )。例如,下面的操作计算集合中的文档数量:

db.collection.aggregate(
   [
      { $group: { _id: null, count: { $sum: 1 } } }
   ]
)

如果想要进行带查询条件的计数,使用 $match 操作符是个好方法:

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

参见 Perform a Count 中的例子。

使用索引

参考包含如下索引的集合:

{ 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 会把文档记录写到内存中,后续再次执行相同的查询时,性能会更好。

例子

下面是 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()

计数时使用 limit 方法

下面的操作计算 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)

指定使用的索引

下面的操作在 orders 集合中使用 { status: 1 } 索引查询并返回 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()