MongoDB Aggregation $group
Introduction
The $group
stage in MongoDB’s aggregation framework is used to group documents by specific fields and perform aggregate operations like counting, summing, or averaging. This tutorial will explain how to use the $group
stage effectively.
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 $group
$group
1. Basic $group
Example
$group
ExampleTo group documents by the item
field and calculate the total quantity sold for each item:
Output:
2. Grouping with Multiple Fields
You can also group by multiple fields. For example, if you want to group by both item
and price
:
Output:
3. Counting Documents
To count the number of documents for each item:
Output:
4. Using $group
with Other Stages
$group
with Other StagesYou can combine $group
with other stages in the aggregation pipeline. For instance, if you want to filter documents before grouping:
Output:
Conclusion
You have learned how to use the $group
stage in MongoDB's aggregation framework to perform various aggregate operations, including summing quantities, counting documents, and grouping by multiple fields.
Feel free to reach out if you have any questions or need further guidance!
Last updated