7 Ways to Count Documents in MongoDB

MongoDB offers various methods for counting the documents in a collection or view. There are also some aggregation operators that enable you to count incoming documents from a previous aggregation pipeline stage.

This article presents the following ways to count documents in the mongo shell:

  • The count command
  • The db.collection.count() method
  • The db.collection.countDocuments() method
  • The db.collection.estimatedDocumentCount() method
  • The cursor.count() method
  • The $count aggregation pipeline operator
  • The $sortByCount aggregation pipeline operator

The count Command

The count command counts the number of documents in a collection or a view.

Example:

db.runCommand( { 
    count: "pets", 
    query: { type: "Dog" } 
} )

Result:

{ "n" : 4, "ok" : 1 }

In this example, we can see that there are four dogs in the pets collection.

We can also see that it returns a document that contains the count as well as the command status.

The db.collection.count() Method

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.

The db.collection.count() method is a wrapper method for the count command.

Example:

db.pets.count({
    "type": "Dog"
})

Result:

4

The db.collection.count() method doesn’t return a document like the count command does. It simply returns the count.

The countDocuments() Method

The db.collection.countDocuments() method returns the count of documents that match the query for a collection or view.

The collection part is the name of the collection or view to perform the count operation on.

Example:

db.pets.countDocuments({
    "type": "Dog"
})

Result:

4

Basically the same result as db.collection.count(), although it’s recommended to use countDocuments() instead of count() if possible.

The MongoDB documentation states:

MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection count() APIs in favor of new APIs for countDocuments() and estimatedDocumentCount(). For the specific API names for a given driver, see the driver documentation.

Also, when used without a query predicate, count() relies on metadata, which may result in an approximate count. The countDocuments() method on the other hand, doesn’t rely on metadata, and returns an accurate count by performing an aggregation of the documents.

The estimatedDocumentCount() Method

The db.collection.estimatedDocumentCount() method is a wrapper for the count command that returns the count of all documents in a collection or view.

Example:

db.pets.estimatedDocumentCount()

Result:

7

The db.collection.estimatedDocumentCount() method doesn’t take a query filter. It instead uses metadata to return the document count for the whole collection/view.

The cursor.count() Method

The cursor.count() method is a wrapper for the count command that counts the number of documents referenced by a cursor..

It doesn’t actually perform the query. It simply counts and returns the number of results that would be returned by the query.

Example:

db.pets.find({"type": "Dog"}).count()

Result:

4

This is equivalent to the db.collection.count() method example above.

As quoted above, MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection count() APIs in favor of new APIs for countDocuments() and estimatedDocumentCount().

The $count Aggregation Pipeline Operator

The $count aggregation operator passes a document to the next stage in the aggregation pipeline that contains a count of the number of documents input to the current stage.

Example:

db.pets.aggregate([
    {
      $match: { type: "Dog" }
    },
    {
      $count: "DogCount"
    }
])

Result:

{ "DogCount" : 4 }

Here’s another example that shows how you can use this operator to count grouped results.

db.pets.aggregate([
    {
      $match: { weight: { $lt: 30 } }
    },
    {
      $group: { _id: "$type", count: { $sum: 1 } }
    },
     { 
      $sort : { count : -1, _id: 1 } 
    }
])

Result:

{ "_id" : "Dog", "count" : 3 }
{ "_id" : "Cat", "count" : 2 }
{ "_id" : "Bat", "count" : 1 }

This particular query can be done with less code by using the $sortByCount aggregation pipeline operator (below).

The $sortByCount Aggregation Pipeline Operator

The $sortByCount aggregation operator groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.

Here’s how we can use $sortByCount to achieve the same result as the previous example:

db.pets.aggregate([
    {
      $match: { weight: { $lt: 30 } }
    },
    {
      $sortByCount: "$type"
    }
])

Result:

{ "_id" : "Dog", "count" : 3 }
{ "_id" : "Cat", "count" : 2 }
{ "_id" : "Bat", "count" : 1 }

Each group is output in its own document, which consists of two fields:

  • an _id field containing the distinct grouping value, and
  • count field containing the number of documents belonging to that grouping.

The documents are sorted by count in descending order.