In this MongoDB tutorial, we will discuss MongoDB aggregate $count with a few examples. Here we will cover the below topics:
- MongoDB aggregate $count query
- MongoDB aggregate $count example
- MongoDB aggregate $count with condition
- MongoDB aggregate $count where
- MongoDB aggregate $count element in array
- MongoDB aggregate $count greater than
- MongoDB aggregate $count unique
- MongoDB aggregate $count match
- MongoDB compass aggregate $count
- MongoDB aggregate $count using python
MongoDB aggregate $count query
In this topic, you will learn about MongoDB aggregate $count. It transfers a document to the next stage that contains a count of the number of documents input to the stage.
The $count has the following form:
{ $count: <string> }
Here, the string is the name of the output field which has the count as its value. And, the string must be a non-empty string, not start with ‘$’ and not contain ‘.’ character.
Note:
The $count stage is equivalent to the following $group + $project.
Read Create index in MongoDB and MongoDB count with examples
MongoDB aggregate $count example
In this topic, you will understand an example of MongoDB $count aggregation. Let’s get understand an example and count the number of documents of a collection.
Example:
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 }
])
The subsequent documents were inserted into the marks collection.
Now, we will apply the below query to the collection to count the number of documents using $count aggregation.
db.marks.aggregate({ $count: "id"})

We have successfully counted the documents using the $count aggregation in MongoDB.
Read MongoDB Auto Increment ID
MongoDB aggregate $count with condition
In this topic, you will learn to apply the condition using the MongoDB $count aggregation. Let’s get understand this with the help of an example and count the number of documents.
Example:
The subsequent 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 the collection where the condition is to count the number of students that scored less than 80 using $count aggregation.
db.marks.aggregate(
[
{
$match: {
score: {
$lt: 80
}
}
},
{
$count: "Number of students that scored less than 80"
}
]
)
Here, the $match stage will exclude documents that have a score value greater than 80. The $count stage returns a count of the remaining documents in the aggregation pipeline and assigns the value to a field called “Number of students that scored less than 80”.
Let’s inspect the output now:

We have successfully counted the documents using the $count aggregation pipeline in MongoDB.
Read MongoDB remove a field from the document
MongoDB aggregate $count where
In this topic, you will study an example where apply a condition using the $count stage and count the number of documents. You will more understand this with the help example so let get started.
Example:
The following documents were inserted into the data collection.
db.data.insertMany([
{ "First_Name" : "Ian", "Last_Name" : "Morse", "Age" : 22, "Born" : 1992 },
{ "First_Name" : "Harry", "Last_Name" : "Potter", "Age" : 24 },
{ "First_Name" : "Steve", "Last_Name" : "Morse", "Age" : 21 },
{ "First_Name" : "Roger", "Last_Name" : "Paice", "Age" : 26 },
{ "First_Name" : "Kim", "Last_Name" : "Janner", "Age" : 29 },
{ "First_Name" : "Tom", "Last_Name" : "Strak", "Age" : 21, "Born" : 1999 }
])
Now, we will apply the below query to count the number of documents using $count aggregation where the Age is 21.
db.data.aggregate([
{
"$match": { "Age": 21 }
},
{
"$count": "number of occurrences"
}
])
Here, The $match stage will check the match field in documents where Age is 21. Next, The $count stage will return the counted documents that fulfil the condition and then we will attach them to the “number of occurrences” field.

We have successfully counted the documents where Age is 21 using the $count aggregation pipeline in MongoDB.
Read MongoDB to find multiple values
MongoDB aggregate $count element in array
In this topic, you will learn to count the elements in the array from the MongoDB collection. For this, MongoDB provides the $size aggregation to count and returns the total number of items in an array. Let’s get understand this with the help of an example.
Example:
The subsequent documents were inserted into the Test collection.
db.Test.insertMany([
{ "_id" : 101, "Name" : "Peter", "Scores" : [ 56, 78 ] },
{ "_id" : 102, "Name" : "Jack", "Scores" : [ 88, 45 ] },
{ "_id" : 103, "Name" : "Jonas", "Scores" : [ 98, 79 ] },
{ "_id" : 104, "Name" : "Bob", "Scores" : [ 98, 79, 80, 92 ] },
{ "_id" : 105, "Name" : "Jasica", "Scores" : [ 91, 80, 92 ] }
])
After that, you have to apply the following query to count the number of elements in the array.
db.Test.aggregate([
{
$project: {
count: { $size: "$Scores" }
}
}
])
Here, we have used the $size to count and returns the total number of items in an array field Scores.
Let’s inspect the output now:

We have successfully counted the number of elements in an array of the MongoDB collection,
Read MongoDB text search partial words
MongoDB aggregate $count greater than
In this topic, you will learn to count the number of documents that are greater than a particular field using MongoDB aggregate $count. Let’s get understand this with the help of an example.
Example:
The subsequent documents were inserted into the library collection.
db.library.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
}
])
Now, we will apply the below query to count the number of documents of the MongoDB library collection that are greater than to a particular field.
db.library.aggregate([
{
$match: {
views: {
$gt: 150
}
}
},
{
$count: "Total books where views are greater than 150"
}
])
Here, we have used the aggregate operation and applied the $gt operation on the views fields to count the number of documents where views are greater than 150.
Let’s inspect the output now:

We have successfully counted the documents of the library collection that are greater than 150.
Read MongoDB find string contains
MongoDB aggregate $count unique
In this MongoDB topic, you will learn to count the unique or distinct fields of values of the collection. So let’s get understand this with the help of 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" }
])
Now, we will apply the below query to count the number of unique fields.
db.review.aggregate([
{
$group: {
_id: "$Age",
count: { $sum: 1 }
}
}
])
Here, we have used the $group stage in the aggregate operation to group the documents by item to retrieve the distinct item values $Age and the $sum operation is used to count for counting all rows from the grouped data.

We have successfully counted the unique field value of the review collection in MongoDB.
MongoDB aggregate $count match
In this MongoDB topic, you will count the number of documents that matches a particular field of a collection. MongoDB provides the $count operation to count the documents. Let’s get understand this followed by an example.
Example:
The subsequent 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 number of documents that matches a value.
db.example.aggregate([
{
$match: {
name: "John"
}
},
{
$count: "Count"
}
])
Here, we have used the $match stage to match a value from the documents where the name is John. After that, the $count operation is used to count the number of documents that satisfy the condition.
Let’s inspect the output now:

We have successfully counted the documents of the collection as per the condition in MongoDB.
Read Missing before statement MongoDB
MongoDB compass aggregate $count
You can count the number of documents using the MongoDB Compass. In this topic, you will understand how MongoDB compass works and how it will count the number of documents. So, let’s get understand this followed by an example.
Example:
You have to follow the below steps to understand the example using MongoDB compass.
- Open the MongoDB Compass and connect to the server.
- Select the existing database and collection where you want to count the number of documents.
- Here, we are using the enterprise collection inside the organisation database.

- After that, we will click on Aggregations to apply the aggregation operation.
- Here, we have applied two aggregate stages $match and $count.
- The $match is used to match the documents and retrieve only documents that satisfy the condition. And, the $count is used to count the number of documents in a collection.

- Here, the $match operation is used to find documents where Year is 2019. And, In the next stage, the $count operation is used to count the number of documents that satisfy the condition.
We have successfully counted the number of documents where the Year is 2019.
Read Sub-process /usr/bin/dpkg returned an error code (1)
MongoDB aggregate $count using python
In this topic, you will understand to count the documents in MongoDB using Python. Python needs a MongoDB driver to access the MongoDB database. So, we will use the MongoDB driver PyMongo to access the MongoDB database. Let’s get understand this followed by an example and count the number of documents in the collection.
Example:
The following documents were inside the Sales collection.
db.Sales.find()
{ "_id" : 1, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : 2, "date" : ISODate("2020-03-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : NumberDecimal("20"), "quantity" : 1, "date" : ISODate("2020-03-01T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : NumberDecimal("5"), "quantity" : 10, "date" : ISODate("2020-03-15T09:00:00Z") }
{ "_id" : 4, "item" : "xyz", "price" : NumberDecimal("5"), "quantity" : 20, "date" : ISODate("2020-04-04T11:21:39.736Z") }
{ "_id" : 5, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : 10, "date" : ISODate("2021-04-04T21:23:13.331Z") }
{ "_id" : 6, "item" : "def", "price" : NumberDecimal("7.5"), "quantity" : 5, "date" : ISODate("2021-06-04T05:08:13Z") }
{ "_id" : 7, "item" : "def", "price" : NumberDecimal("7.5"), "quantity" : 10, "date" : ISODate("2021-09-10T08:43:00Z") }
{ "_id" : 8, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : 5, "date" : ISODate("2021-02-06T20:20:13Z") }
You can retrieve the documents by using the find() method.

Now, we will use the following block of python code to count the number of documents of the Sales collection:
import pymongo
# creating a MongoClient object and connect with the host
myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017")
# accessing the database
mydb = myclient["mydatabase"]
# accessing the collection of the database
mycol = mydb["Sales"]
# count the total number of documents
collect = mycol.aggregate([ { "$count": "Total number of documents" } ])
for count_documents in collect:
print(count_documents)
In the code, we have imported the pymongo library to access the MongoDB driver.
- After that, connect with the server.
- Access the MongoDB Sales collection of the mydatabase database.
- After that, we have applied the $count aggregate operation to count the number of documents.
Let’s inspect the output now:

We have successfully counted the total number of documents of an existing collection ‘Sales’ of MongoDB using python.
You may like the following MongoDB tutorials:
- MongoDB two-phase commit
- MongoDB shutting down with code 48
- MongoDB create and change user password
- MongoDB find multiple conditions
- MongoDB Update Documents
In this tutorial, we learned MongoDB aggregate $count with a few examples.
- MongoDB aggregate $count query
- MongoDB aggregate $count example
- MongoDB aggregate $count with condition
- MongoDB aggregate $count where
- MongoDB aggregate $count element in array
- MongoDB aggregate $count greater than
- MongoDB aggregate $count unique
- MongoDB aggregate $count match
- MongoDB compass aggregate $count
- MongoDB aggregate $count using python
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.