MongoDB count with examples

In this MongoDB tutorial, we are going to learn everything about MongoDB count with a few examples. We will cover this by performing various operations with examples. The following list topics we are going to cover in this tutorial:

  • MongoDB count query
  • MongoDB count documents
  • MongoDB count with condition
  • MongoDB count where
  • MongoDB count with limit
  • MongoDB count return 0
  • MongoDB count the number of records in a collection
  • MongoDB count unique values
  • MongoDB count matching documents
  • MongoDB count documents by field value
  • MongoDB count vs countdocuments

MongoDB count query

In this topic, you will learn the MongoDB query. It is used to return the count of documents that would match a find() query for the collection or view.

Syntax:

db.collection.count(query, options)

The “db.collection.count()” method does not perform the find() operation but alternatively counts and return the number of results that matches a query.

ParameterTypeDescription
querydocumentThe query selection criteria.
optionsdocumentsOptional, Extra options for modifying the count.

The options document contains the following fields:

Field TypeDescription
limitintegerOptional, Maximum number of documents to count.
skipintegerOptional, Number of documents to skip before counting.
hintstring or documentOptional. An index name hint or specification for the query.
maxTimeMSintegerOptional, Maximum amount of time to allow the query to run.

Read MongoDB to get collection size

MongoDB count documents

In this MongoDB topic, you will learn to count the number of documents of a collection using the count() method. Let us understand with the help of an example.

Example:

The following documents we had inserted into the marks collection.

db.marks.find()
{ "_id" : 1, "subject" : "History", "score" : 88 }
{ "_id" : 2, "subject" : "Science", "score" : 92 }
{ "_id" : 3, "subject" : "Math", "score" : 97 }
{ "_id" : 4, "subject" : "English", "score" : 88 }
{ "_id" : 5, "subject" : "Hindi", "score" : 69 }
{ "_id" : 6, "subject" : "Social Science", "score" : 80 }
{ "_id" : 7, "subject" : "Computer", "score" : 73 }

Now, we will use the below query to count the documents:

db.marks.count()

Let’s check the output now:

MongoDB count documents
MongoDB count documents

We have successfully counted the total number of documents of a collection in MongoDB.

Read SocketException: Address already in use MongoDB

MongoDB count with condition

In this MongoDB topic, you will learn to count all documents that match the condition. Let us understand this with help of an example and count the documents.

Example:

In this example, the condition is to count the documents where the date is less than.

We have inserted the following documents into the “blogs” collection.

db.blogs.find()
{ "_id" : ObjectId("611de5c86cc7e05e5e7fe745"), "timestamp" : ISODate("2020-04-01T00:00:00Z") }
{ "_id" : ObjectId("611de5e06cc7e05e5e7fe746"), "timestamp" : ISODate("2021-11-11T05:24:05.343Z") }
{ "_id" : ObjectId("611de6196cc7e05e5e7fe747"), "timestamp" : ISODate("2020-05-02T00:00:00Z") }

Now, we will apply the below query to count the number of the documents in the blogs‘ collection where the field timestamp is less than to date(11/11/2021).

db.blogs.count( { timestamp: { $lt: new Date('11/11/2021') } } )

Let’s check the output now:

MongoDB count with condition
MongoDB count with condition

We have successfully counted the number of documents that satisfy the condition in MongoDB.

Read $in MongoDB Example

MongoDB count where

In this MongoDB topic, you will learn to count the number of documents by applying the where condition. Let’s get understand this followed by an example.

Example:

The following documents were inserted into the review collection.

db.review.insertMany([
{ "_id" : 1, "Name" : "David", "Age" : 22, "Gender" : "Male" },
{ "_id" : 2, "Name" : "Peter", "Age" : 24, "Gender" : "Male" },
{ "_id" : 3, "Name" : "Sammy", "Age" : 23, "Gender" : "Female" },
{ "_id" : 4, "Name" : "MARY", "Age" : 21, "Gender" : "Female" },
{ "_id" : 5, "Name" : "Paul", "Age" : 24, "Gender" : "Male" },
{ "_id" : 6, "Name" : "Patrick", "Age" : 25, "Gender" : "Female" }
])

After that, we will apply the below query to count the documents where gender is male.

db.review.count( { Gender: "Male"} )

Let’s check the output now:

MongoDB count where
MongoDB count where

We have successfully counted the total number of documents where Gender is Male in MongoDB.

Read Current date in MongoDB

MongoDB count with limit

In this MongoDB topic, you will learn to count the documents using the limit function. You have to use the true parameter with the count() method that is used to consider the limit values in the calculation. You will more understand this with the help of an example.

Note: By default, the count() ignores the limit() and counts the results in the entire query. So to resolve this, we will use the true parameter with the count() that is used to consider the limit values in the calculation.

Example:

The following documents were inserted into the car collection.

db.car.insertMany([
{ "_id" : 1, "name" : "Audi", "color" : "Red", "cno" : "C101", "mfdcountry" : "Germany", "speed" : 75 },
{ "_id" : 2, "name" : "Swift", "color" : "Black", "cno" : "C102", "mfdcountry" : "Italy", "speed" : 60 },
{ "_id" : 3, "name" : "Tesla", "color" : "Blue", "cno" : "C103", "mfdcountry" : "USA", "speed" : 100 },
{ "_id" : 4, "name" : "Polo", "color" : "White", "cno" : "C104", "mfdcountry" : "Japan", "speed" : 65 },
{ "_id" : 5, "name" : "Audi", "color" : "Black", "cno" : "G101", "mfdcountry" : "Germany", "speed" : 90 },
{ "_id" : 6, "name" : "Volkswagen", "color" : "JetBlue", "cno" : "C105", "mfdcountry" : "Rome", "speed" : 80 }
])

Now, we will apply the below query to count the documents using the limit() function.

db.car.find( { color: "Black"} ).limit(4).count(true)

Here, we have defined the condition in the find method to return documents where the color is Black. And, the limit function is used to return the defined number of documents where the count(true) is used to consider the limit values in the calculation.

Let’s inspect the output now:

MongoDB count with the limit
MongoDB count with the limit

We have successfully counted the total number of documents using the limit function in MongoDB.

Read Display MongoDB data in HTML

MongoDB count return 0

In this MongoDB topic, you will understand why the MongoDB count returns 0. There could be 2 reasons for getting 0 while counting the number of documents from the collection.

  • First, when we count the number of documents to a particular collection and there is no collection of that name in the database then it returns 0.
MongoDB count return 0
MongoDB count return 0

Here, you can see we are using the info database and there are only 4 collections in the database. And, when we count the number of documents in the stores’ collection then it returns 0 because there is no stores’ collection in the info database.

Solution

To resolve this, you have to check once before selecting the collection and then count the number of documents.

  • Second, many times we do backup and restore our MongoDB database. And, when we are restoring our source MongoDB database sometimes it breaks and then it returns 0 or errors.

Solution

To resolve this you have to move or restore the data into a new database. After that, you can easily count the number of documents from the collection using the MongoDB count() method.

Read Distinct query in MongoDB

MongoDB count number of records in a collection

In this MongoDB topic, you will learn to count the number of records in a collection. For that, you can use the below any of the queries to count the number of records.

db.collection_name.count()

This operation is equivalent to the following:

db.collection_name.find().count()

Example:

Here, we will use the same collection car as we have used in the previous topic. For reference check out:

Count number of records in a collection
Count number of records in a collection

Now, you can apply any of the above queries to count the number of documents.

db.car.find().count()

Let’s inspect the output now:

MongoDB count number of records
Count number of records

We have successfully counted the number of records of a collection in MongoDB.

Read MongoDB find by ID

MongoDB count unique values

In this topic, you will learn to count the unique values from the MongoDB collection. We will use distinct() rather than find() and length rather than count() to count the unique values. Let get understand this with the help of an example.

Note:

The count() function does not work on the results of a distinct query.

Example:

The following documents were inserted into the example collection.

db.example.insertMany([
{ "_id" : 1, "name" : "John", "address" : "USA" },
{ "_id" : 2, "name" : "Peter", "address" : "United States" },
{ "_id" : 3, "name" : "Amy", "address" : "Canada" },
{ "_id" : 4, "name" : "Hannah", "address" : "United Kingdom" },
{ "_id" : 5, "name" : "Michael", "address" : "Australia" },
{ "_id" : 6, "name" : "John", "address" : "New Zealand" }
])

Now, we will apply the below query to count the unique values from the documents.

db.example.distinct("name").length

Here, the first argument is distinct in the field that is used to aggregate distinct values of the name field. And then append the length at the end of the query to count the number of rows returned.

MongoDB count unique values
MongoDB count unique values

We have successfully counted the unique or distinct values from the MongoDB collection.

Read MongoDB data directory /data/db not found

MongoDB count matching documents

In this topic, you will learn to count matching documents in MongoDB. When you have a large dataset and you have to count the number of documents as per the defined condition. let us understand this with the help of an example.

Example:

The following documents were inserted into the board collection.

db.board.insertMany([
{ "_id" : 1, "book" : "MongoDB in Action", "author" : " Kyle Banker", "views" : 150 },
{ "_id" : 2, "book" : "Scaling MongoDB", "author" : "Kristina Chodorow", "views" : 106 },
{ "_id" : 3, "book" : "MongoDB and PHP", "author" : "Steve Francia", "views" : 190 },
{ "_id" : 4, "book" : "Mongodb for Web Development", "author" : "Mitch Pirtle", "views" : 160 },
{ "_id" : 5, "book" : "The Little MongoDB Book", "author" : "Karl Seguin", "views" : 200 }
])

Now, we will apply the below query to count matching documents where the condition is the views field value is greater than equal 150.

db.board.find({"views": {"$gte": 150 } }).count()

Here, the count() function is used to count the documents where the field views value is greater than equal 150.

MongoDB count matching documents
MongoDB count matching documents

We have successfully counted the number of documents where views are greater than 150 in MongoDB.

Also read, MongoDB compare two fields

MongoDB count documents by field value

In this MongoDB topic, you will learn to use the MongoDB countDocuments() method to count the number of documents that match the selection criteria. It returns a numeric value that describes the total number of documents that match the selection criteria.

Syntax:

db.Collection_name.countDocuments(
      <Selection_criteria>,
      {
            limit: <integer>,
            skip: <integer>,
            hint: <string or document>,
            maxTimeMS: <integer>,  
      }
)

It takes two arguments first one is the selection criteria and the other is optional. And, This method returns the number of documents that match to selection criteria.

Example:

The following documents were inserted into the marks collection.

db.marks.insertMany([
{ "_id" : 1, "subject" : "History", "score" : 88 },
{ "_id" : 2, "subject" : "Science", "score" : 92 },
{ "_id" : 3, "subject" : "Math", "score" : 97 },
{ "_id" : 4, "subject" : "English", "score" : 88 },
{ "_id" : 5, "subject" : "Hindi", "score" : 69 },
{ "_id" : 6, "subject" : "Social Science", "score" : 80 },
{ "_id" : 7, "subject" : "Computer", "score" : 73 }
])

Now, we will apply the below query to count documents that match the given selection criteria:

db.marks.countDocuments({"score":{ "$gt": 80} })

Here, we have applied the $gt operation, count the documents where the score is greater than 80.

MongoDB count documents by field value
MongoDB count documents by field value

We have successfully applied the countDocuments() method and counted the documents where the score is greater than 80.

Read MongoDB remove an element from the array

MongoDB count vs countdocuments

In this topic, you will read about the difference between the MongoDB count() and countDocument() method. These both are compatible with MongoDB 4.0.

The ‘db.collection.count()’ method without a query predicate and the method returns results based on the collection’s metadata, which may result in an approximate count.

The ‘db.collection.countDocuments(query)’ will return the count of documents that match the query for a collection or view. This method you have to use to count the number of documents in your collection.

Most of the time, the countDocuments() method only returns the actual count of the documents. Apart from this, the other methods use the metadata to count based upon the collection.

You may like the MongoDB tutorials:

I hope you have learned about MongoDB count with a few examples and cover the below topics:

  • MongoDB count query
  • MongoDB count documents
  • MongoDB count with condition
  • MongoDB count where
  • MongoDB count with limit
  • MongoDB count return 0
  • MongoDB count number of records in a collection
  • MongoDB count unique values
  • MongoDB count matching documents
  • MongoDB count documents by field value
  • MongoDB count vs countdocuments