db.collection.countDocuments()
Definition
mongo
Shell Method
This page documents the mongo
shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.
New in version 4.0.3.
Returns the count of documents that match the query for a collectionor view. The method wraps the $group
aggregation stagewith a $sum
expression to perform the count and isavailable for use in Transactions.
- db.collection.countDocuments( <query>, <options> )
ParameterTypeDescriptionquerydocumentThe query selection criteria. To count all documents, specifyan empty document. See also Query Restrictions.optionsdocumentOptional. Extra options that affects the count behavior.
The options
document can contain the following:
FieldTypeDescriptionlimit
integerOptional. The maximum number of documents to count.skip
integerOptional. The number of documents to skip before counting.hint
string or documentOptional. An index name or the index specification to use for the query.maxTimeMS
integerOptional. The maximum amount of time to allow the count to run.
Behavior
Mechanics
Unlike db.collection.count()
,db.collection.countDocuments()
does not use the metadata toreturn the count. Instead, it performs an aggregation of the documentto return an accurate count, even after an unclean shutdown or in thepresence of orphaned documents in a shardedcluster.
db.collection.countDocuments()
wraps the followingaggregation operation and returns just the value of n
:
- db.collection.aggregate([
- { $match: <query> },
- { $group: { _id: null, n: { $sum: 1 } } } )
- ])
Empty or Non-Existing Collections and Views
Starting in version 4.2.1 (and 4.0-series in 4.0.13),db.collection.countDocuments()
returns 0
on an empty ornon-existing collection or view.
In earlier versions of MongoDB, db.collection.countDocuments()
errors on an empty or non-existing collection or view.
Query Restrictions
You cannot use the following query operators as part of the queryexpression for db.collection.countDocuments()
:
Restricted Operator | Alternative |
---|---|
$where | As an alternative, use $expr instead. |
$near | As an alternative, use $geoWithin with $center ; i.e.
|
$nearSphere | As an alternative, use $geoWithin with $centerSphere ; i.e.
|
Transactions
db.collection.countDocuments()
can be used inside multi-document transactions.
Important
In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.
For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.
Client Disconnection
Starting in MongoDB 4.2, if the client that issued the db.collection.countDocuments()
disconnects before the operation completes, MongoDB marksthe db.collection.countDocuments()
for termination (i.e. killOp
on theoperation).
Examples
Count all Documents in a Collection
To count the number of all documents in the orders
collection, usethe following operation:
- db.orders.countDocuments({})
Count all Documents that Match a Query
Count the number of the documents in the orders
collection with the field ord_dt
greater than newDate('01/01/2012')
:
- db.orders.countDocuments( { ord_dt: { $gt: new Date('01/01/2012') } }, { limit: 100 } )
See also