MongoDB count() method
MongoDB count is accustomed to counting the nunber of a document from collections. We have tracked down the number of documents using the count method in MongoDB. We have used the find method to display all the documents of a collection. But, if we need to know the actual count of the documents, then we should use the count method.
MongoDB count() method returns the number of results in a specified collection or number of documents that match in a find() query. We cannot use this method in transactions.
Syntax of count()
db.collection.count(query, options)
Here, the count() returns only number of results that match a query. The parameter 'query' is the selection criteria, The type of this argument is a document. The second parameter is an optional, like - limit, skip, hint and are optional.
Optional parameters with count query in MongoDB:
Parameter |
Description |
---|---|
count | Count the collection or view documents |
query | The query selection criteria. |
limit | The maximum number of documents to count. |
skip | The number of documents to skip before counting. |
hint | An index name hint(specification) for the query. |
readConcern | The default read concern level of MongoDB is local. |
collation | It specifies the collation to use for the operation. |
Example: Count all documents from a collection
The following statement returns total number of students in a collection.
db.students.count();

Example: Count documents that match a query
In the given example, we have counted the documents that match query from 'students' table using count method in MongoDB.
db.runCommand({count:'students', query: {"age":11}})

MongoDB count() with find()
We can use the count() method with find() query. The given statement returns total number of students of class '5C'.
db.students.find({"class": "5C"}).count();
