OPTIONS

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.

Changed in version 2.6: MongoDB supports the use of hint() with count(). See Specify the Index to Use for an example.

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.

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

See also

cursor.size()

Examples

The following are examples of the count() method.

Count All Documents

The following operation counts the number of all documents in the orders collection:

db.orders.find().count()

Count Documents That Match a Query

The following operation counts 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()

Limit Documents in Count

The following operation counts 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)

Specify the Index to Use

The following operation uses the index { status: 1 } to return a count of the documents in the orders collection with the field ord_dt greater than new Date('01/01/2012') and the status field is equal to "D":

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