In mongodb, we can count document in multiple ways. Some ways are deprecated, and some are newly introduced. Let see all possible method to count the documents.
Table of Contents
1. db.collection.count()
db.collection.count(query, options)
Returns the count of documents that would match a find()
query for the collection or view. The db.collection.count()
method does not perform the find()
operation but instead counts and returns the number of results that match a query.
Examples:
Count all Documents in a Collection
To count the number of all documents in the orders
collection, use the following operation:
db.orders.count()
Count all Documents that Match a Query
Count the number of the documents in the orders
collection with the field ord_dt
greater than new Date('01/01/2012')
:
db.orders.count( { ord_dt: { $gt: new Date('01/01/2012') } } )
2. cursor.count()
db.collection.find(<query>).count()
Counts the number of documents referenced by a cursor. Append the count()
method to a find()
query to return the number of matching documents. The operation does not perform the query but instead counts the results that would be returned by the query.
Examples:
The following operation counts the number of all documents in the orders
collection:
db.orders.find().count()
Count Documents That Match a Query
The following operation counts the number of the documents in the orders
collection with the field ord_dt
greater than new Date('01/01/2012')
:
db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()
The following operation counts the number of the documents in the orders
collection with the field ord_dt
greater than new Date('01/01/2012')
taking into account the effect of the limit(5)
:
db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).limit(5).count(true)
Note: By default, the cursor.count()
method ignores the effects cursor.skip()
and cursor.limit()
. To consider effect of these method we need to pass true
in cursor.count()
Point to remember:
When we use count()
OR count()
on a find()
without a query predicate, we may get inaccurate document counts. Without a query predicate, these count()
methods use collection’s metadata for document count, which may result in an approximate count. In particular,
- On a sharded cluster, OR
- After an unclean shutdown or file copy based initial sync, the count may be incorrect.
MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection
count()
APIs in favor of new APIs that corresponds tocountDocuments()
andestimatedDocumentCount()
.
3. db.collection.estimatedDocumentCount()
db.collection.estimatedDocumentCount( <options> )
Returns the count of all documents in a collection or view. db.collection.estimatedDocumentCount()
does not take a query filter and instead uses metadata to return the count for a collection. For View
the document count is calculated by executing the aggregation pipeline
in the view definition.
Point to Remember:
- On a sharded cluster, the resulting count will not correctly filter out orphaned documents.
- After an unclean shutdown, the count may be incorrect. This is applicable only to collection not View
Example
The following example uses db.collection.estimatedDocumentCount()
to retrieve the count of all documents in the orders
collection:
db.orders.estimatedDocumentCount({})
4. db.collection.countDocuments()
db.collection.countDocuments(query, options)
Returns the count of documents that match the query for a collection or view. This method is available for use in Transactions.
Unlike db.collection.count()
, db.collection.countDocuments()
does not use the metadata to return the count. Instead, it performs an aggregation of the document to return an accurate count, even after an unclean shutdown or in the presence of orphaned documents in a sharded cluster.
Examples
Count all Documents in a Collection
To count the number of all documents in the orders
collection, use the 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 new Date('01/01/2012')
:
db.orders.countDocuments( { ord_dt: { $gt: new Date('01/01/2012') } }, { limit: 100 } )
Point to remember that
- You cannot use the
$where, $near
and,$nearSphere
query operators as part of the query expression fordb.collection.countDocuments()
: - From mongodb 4.2.1,
db.collection.countDocuments()
returns0
on an empty or non-existing collection or view. But earlier version give error for same.
5. $sum
When used in the $group
stages, $sum
has this syntax:
{ $sum: <expression> }
With some filter conditions
db.collection.aggregate([
{ $match: <query> },
{ $group: { _id: null, count: { $sum: 1 } } }
{ $project: { _id: 0 } }
])
Without any conditions
db.collection.aggregate( [
{ $group: { _id: null, count: { $sum: 1 } } }
{ $project: { _id: 0 } }
] )
Examples
Count all Documents in a Collection
To count the number of all documents in the orders
collection, use the following operation:
db.orders.aggregate([
{ $group: { _id: null, count: { $sum: 1 } } }
{ $project: { _id: 0 } }
])
Count all Documents that Match a Query
Count the number of the documents in the orders
collection with the field ord_dt
greater than new Date('01/01/2012')
:
db.order.aggregate(
[
{ $match: {ord_dt:{ $gt: new Date('01/01/2012')}}},
{ $group: { _id: null, count: { $sum: 1 } } }
{ $project: { _id: 0 } }
]
)
6. $count
$count
syntax:
{ $count: { } }
$count
does not accept any parameters. $count
is functionally equivalent to using { $sum : 1 }
within the $group
stage.
db.collection.aggregate({$count:"Any Name"})
Examples
Count all Documents in a Collection
To count the number of all documents in the orders
collection, use the following operation:
db.orders.aggregate({$count:"count"})
Count all Documents that Match a Query
Count the number of the documents in the orders
collection with the field ord_dt
greater than new Date('01/01/2012')
:
db.order.aggregate(
[
{ $match: {ord_dt:{ $gt: new Date('01/01/2012')}}},
{$count: "count"}
]
)
7. $collStats
db.collection.aggregate( [ { $collStats: { count: { } } }, { $prject:{count:1} ] )
Example
Count all Documents in a Collection
To count the number of all documents in the orders
collection, use the following operation:
db.order.aggregate( [ { $collStats: { count: { } } }, { $prject:{count:1} ] )
The count is based on the collection’s metadata, which provides a fast but sometimes inaccurate count for sharded clusters.
Source : MongoDb Doc