countDocuments() – Find the number of documents, or rows, in a collection command

Finds the number of documents, or the number of rows, in a collection.

Syntax diagram

Read syntax diagramSkip visual syntax diagramdb.collection. countDocuments(query)
Read syntax diagramSkip visual syntax diagramdb.collection. countDocuments()

Command parameters

query
A JSON query to filter a subset of data.

Examples

The following example shows the command syntax for returning the number of documents in the collection, books:
db.books.countDocuments()
The following example shows the output returned by the previous example:
15
The following example shows the command syntax for returning the number of documents for a specified author:
db.books.countDocuments({ author: "Tolkien, J.R" })
The following example shows the output returned from the countDocuments operation:
2