Navigation
This version of the documentation is archived and no longer supported.

cursor.count()

Definition

cursor.count()

Counts the number of documents referenced by a cursor. Append the count() method to a find() query to return the number of matching documents. The operation does not perform the query but instead counts the results that would be returned by the query.

The count() method has the following prototype form:

db.collection.find().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.

See also

cursor.size()

MongoDB also provides the shell wrapper db.collection.count() for the db.collection.find().count() construct.

See also

cursor.size()

Behavior

On a sharded cluster, count() method can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.

To avoid these situations, on a sharded cluster, use the $group stage of the db.collection.aggregate() method to $sum the documents. For example, the following operation counts the documents in a collection:

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

To get a count of documents that match a query condition, include the $match stage as well:

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

See Perform a Count for an example.

Examples

The following are examples of the count() method.

Example

Count the number of all documents in the orders collection:

db.orders.find().count()

Example

Count the number of the documents in the orders collection with the field ord_dt greater than new Date('01/01/2012'):

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

Example

Count the number of the documents in the orders collection with the field ord_dt greater than new Date('01/01/2012') taking into account the effect of the limit(5):

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