MongoDB count() Method – db.Collection.count()
The count() method counts the number of documents that match the selection criteria. It returns the number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and the other is optional.
- This method is equivalent to db.collection.find().count().
- You cannot use this method in transactions.
- One a shared cluster, if you use this method without a query predicate, then it will return an inaccurate count if orphaned documents exist or if a chunk migration is in progress. So, to avoid such type of situation use db.collection.aggregate() method
hint: <string or document>,
maxTimeMS : <integer>,
Or if we want to count the number of documents in the collection then use this syntax:
- The first parameter is a selection criteria. The type of this parameter is a document.
- The second parameter is optional.
- limit: It is the maximum number of documents to count.
- skip: It is the number of documents to skip before counting.
- hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.
- maxTimeMs: It is the maximum amount of time to allow the query to run.
- readConcern: It is used when you don’t want to use default read concern. To use a read concern level of “majority”, you must specify a nonempty query condition.
- collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
This method returns the number of documents that match to selection criteria.
In the following examples, we are working with:
Document: Four documents contains name and age of the students
- Count the number of documents in the given collection:
Here, we count the total number of documents present in the student collection.
- Count the number of documents that match the given collection:
Here, we count the total number of documents in the student collection that matches the given condition, i.e., age is greater than 18.
Note: Here, $gt mean greater than