In MongoDB the db.collection.count()
method returns the count of documents that would match a find()
query for the collection or view.
The collection
part is the name of the collection or view to perform the count operation on.
Note that it doesn’t actually perform a find()
operation. It simply counts and returns the number of results that match a query.
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.count()
Result:
7
This is the equivalent of doing the following:
db.pets.find().count()
Result:
7
The MongoDB documentation actually advises against using db.collection.count()
without a query predicate. This is because the method returns results 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.
Example:
db.pets.count({
"type": "Dog"
})
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.count({
"weight": { $gt: 10 }
})
Result:
3
Limit the Count
You can use the limit
parameter to specify a maximum number of documents to count.
Example:
db.pets.count( {}, { limit: 5 } )
Result:
5
We saw before that there are actually 7 documents in this collection, but in this example we limited it to count a maximum of 5.
If the limit is higher than the actual count, then the result won’t be affected by the limit
argument.
Example:
db.pets.count( {}, { limit: 10 } )
Result:
7
Skipping Documents
You can count use the skip
parameter to skip a number of documents before counting.
Example:
db.pets.count( {}, { skip: 5 } )
Result:
2
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 forcountDocuments()
andestimatedDocumentCount()
. For the specific API names for a given driver, see the driver documentation.
More Information
The db.collection.count()
method is a wrapper for the count
command.
The db.collection.count()
method accepts other parameters, such as hint
, maxTimeMS
, readConcern
, and collation
.
See the MongoDB documentation for more information.