MongoDB cursor.count()

In MongoDB the cursor.count() method counts the number of documents referenced by a cursor..

Note that it doesn’t actually perform the query. It simply counts and returns the number of results that would be returned by the query.

The cursor.count() method is a wrapper for the count command.

Example

Suppose we have a collection called pets with the following documents:

{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }
{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }
{ "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 }
{ "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 }
{ "_id" : 6, "name" : "Fetch", "type" : "Dog", "weight" : 17 }
{ "_id" : 7, "name" : "Jake", "type" : "Dog", "weight" : 30 }

We can use the following query to return the number of documents in the collection:

db.pets.find().count()

Result:

7

This is the equivalent of doing the following:

db.pets.count()

Result:

7

The MongoDB documentation actually advises against using cursor.count() when the find() method is called without a query predicate. This is because in such cases, the results are based on the collection’s metadata, which may result in an approximate count.

Count the Result of a Query

You can count the result of a query by passing the query criteria to the find() method.

Example:

db.pets.find({"type": "Dog"}).count()

Result:

4

In this example, we found out that there are four dogs in the collection.

Let’s check the count of another query. This time we’ll find out how many pets have a weight greater than a certain amount.

db.pets.find({"weight": { $gt: 10 }}).count()

Result:

3

Deprecation

Note that the MongoDB documentation states the following:

MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection count() APIs in favor of new APIs for countDocuments() and estimatedDocumentCount(). For the specific API names for a given driver, see the driver documentation.

The applySkipLimit Parameter

The cursor.count() method accepts one optional parameter: the applySkipLimit parameter.

This parameter specifies whether to consider the effects of the cursor.skip() and cursor.limit() methods in the count.

By default, it ignores any effects of those two methods. To include the effects, use appySkipLimit: true.

More Information

See the MongoDB documentation for more information.