MongoDB Aggregation $count
Introduction
The $count
stage in MongoDB's aggregation framework is used to count the number of documents that pass through the pipeline and returns the count as a document with a specified field name. This stage is useful for obtaining a total count of documents based on certain criteria or conditions after applying various stages of the aggregation pipeline.
Prerequisites
MongoDB installed and running on your machine.
Access to
mongosh
and a populated database with sample data.
Step 1: Start mongosh
mongosh
Open Terminal/Command Prompt:
Launch your terminal (macOS/Linux) or command prompt (Windows).
Start
mongosh
:Type the following command and press Enter:
Step 2: Switch to the Database
Switch to the database where your collection is located.
Use a Database:
Step 3: Sample Data
Let’s assume you have a collection named sales
with documents that look like this:
Step 4: Using $count
$count
1. Basic Usage of $count
$count
To count the total number of documents in the sales
collection, you can use the $count
stage at the end of your aggregation pipeline. For example:
Output:
2. Counting After Filtering
You can also count the documents after applying certain conditions using $match
followed by $count
. For example, to count how many items are in the fruit
category:
Output:
3. Counting with Multiple Conditions
You can use $match
to filter documents based on multiple conditions before counting. For example, to count the number of fruits with a quantity greater than 5:
Output:
4. Combining $count
with Other Stages
$count
with Other StagesYou can combine $count
with other aggregation stages for more complex analyses. For example, if you want to group items by category and then count how many items are in each category, you can use $group
followed by $count
:
Output:
5. Counting Documents in a Sub-Pipeline
You can also use $count
in a sub-pipeline if you want to count documents at a certain stage of your aggregation. For example, to count the number of documents after some transformations:
Output:
Conclusion
You have learned how to use the $count
stage in MongoDB's aggregation framework to count documents based on specified criteria and conditions. This stage is essential for analyzing data and obtaining aggregate counts that can be useful for reporting and data insights.
Feel free to reach out if you have any questions or need further guidance!
Last updated