Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
Aggregation in MongoDB
Next article icon

MongoDB Aggregation $group Command

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The $group command in MongoDB's aggregation framework is a powerful tool for performing complex data analysis and summarization. It allows users to group documents based on specified keys and apply aggregate functions such as sum, count, average, min, max, and more.

In this article, we will explore MongoDB Aggregation $group command in detail, covering its syntax, key functions, use cases, and examples to help beginners and professionals efficiently analyze their data

MongoDB Aggregation $group

The $group command is an important aggregation pipeline stage that enables grouping of documents and applying aggregate functions on the grouped data. It is commonly used for data analysis, reporting, and summarization. Along with basic aggregate functions like sum, count, and average the $group supports a variety of other operations such as finding the maximum or minimum value in a group, concatenating strings and calculating standard deviations.

Key Features of $group Command

  • Groups documents based on a specified field or expression
  • Supports multiple aggregation operations such as $sum, $count, $avg, $max, and $min
  • Allows grouping by multiple fields for more detailed analysis
  • Can be combined with other aggregation stages like $match, $sort, and $project
  • Helps in summarizing large datasets efficiently

Syntax:

The basic syntax of the $group command is as follows:

{

$group: {

_id: <expression>,

<field1>: { <accumulator1>: <expression1> },

<field2>: { <accumulator2>: <expression2> }

}

}

Key Terms

  • $_id -> The field used to group documents. It can be an existing field or a computed expression.
  • <field1>, <field2> -> Fields to include in the output.
  • <accumulator1>, <accumulator> -> Aggregate functions to apply to grouped data.
  • <expression>, <expression> -> Expressions to compute values for grouping or aggregation.

Examples of $group Command in MongoDB

The $group command is widely used for aggregating and analyzing data in MongoDB. It helps in summarizing sales, counting occurrences, and computing statistics efficiently. To illustrate its usage, let's consider a sales collection that stores sales transactions, where each document includes details such as product, category, and amount. Below is a sample dataset:

Sample Data:

[
{
"product": "Product A",
"category": "Category 1",
"amount": 100
},
{
"product": "Product B",
"category": "Category 2",
"amount": 150
},
{
"product": "Product C",
"category": "Category 1",
"amount": 120
},
{
"product": "Product D",
"category": "Category 2",
"amount": 200
}
]

Example 1: Count the Number of Documents in a Collection

This query calculates the total number of documents present in the sales collection, providing a quick way to determine the dataset size.

Query:

db.sales.aggregate([
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
])

Output:

[
{
"_id": null,
"count": 4
}
]

Explanation:

  • _id: null → Groups all documents together without a specific field.
  • $sum: 1 → Adds 1 for each document, effectively counting the total number of documents.
  • The result shows that there are 4 documents in the sales collection

Example 2. Retrieve Distinct Values

This query retrieves unique category values from the sales collection, helping identify different product categories available in the dataset.

Query:

db.sales.aggregate([
{
$group: {
_id: "$category"
}
}
])

Output:

[
{ "_id": "Category 1" },
{ "_id": "Category 2" }
]

Explanation:

  • _id: "$category" → Groups documents by the category field, effectively extracting distinct category values.
  • The result lists the unique categories present in the sales collection, which are "Category 1" and "Category 2".
  • This approach is useful for filtering unique values in large datasets efficiently.

Example 3: Group by Item Having

This query groups documents by category and calculates the total sales amount for each category in the sales collection

Query:

db.sales.aggregate([
{
$group: {
_id: "$category",
totalAmount: { $sum: "$amount" }
}
}
])

Output:

[
{ "_id": "Category 1", "totalAmount": 220 },
{ "_id": "Category 2", "totalAmount": 350 }
]

Explanation:

  • _id: "$category" → Groups documents by the category field.
  • $sum: "$amount" → Adds up the amount values for each category.
  • The result shows that Category 1 has a total sales amount of 220, while Category 2 has 350.
  • This query is useful for financial analysis, revenue tracking, and sales reporting

Example 4: Calculate Count, Sum, and Average

This query groups documents by category and calculates the total count of documents, sum of sales amount, and average sales amount per category in the sales collection.

Query:

db.sales.aggregate([
{
$group: {
_id: "$category",
count: { $sum: 1 },
totalAmount: { $sum: "$amount" },
averageAmount: { $avg: "$amount" }
}
}
])

Output:

[
{
"_id": "Category 1",
"count": 2,
"totalAmount": 220,
"averageAmount": 110
},
{
"_id": "Category 2",
"count": 2,
"totalAmount": 350,
"averageAmount": 175
}
]

Explanation:

  • _id: "$category" → Groups documents by category.
  • $sum: 1 → Counts the number of documents in each category.
  • $sum: "$amount" → Computes the total sales amount per category.
  • $avg: "$amount" → Calculates the average sales amount per category.
  • The result shows that Category 1 has 2 transactions, with a total amount of 220 and an average amount of 110, while Category 2 has 2 transactions, with a total amount of 350 and an average amount of 175

Exampl 5: Group by null

This query calculates the total sum of the amount field across all documents in the sales collection, without grouping by any specific field.

Query:

db.sales.aggregate([
{
$group: {
_id: null,
totalAmount: { $sum: "$amount" }
}
}
])

Output:

[
{ "_id": null, "totalAmount": 570 }
]

Explanation:

  • _id: null → Groups all documents together as a single group, meaning the entire collection is aggregated.
  • $sum: "$amount" → Computes the total sum of the amount field across all documents.
  • The output shows that the total sales amount in the collection is 570.

Best Practices for Using $group in MongoDB

1. Use Indexing for Better Performance – Index fields used in grouping to speed up queries.
2. Optimize Aggregation Pipelines – Apply $match before $group to filter unnecessary documents.
3. Avoid Grouping on Large Fields – Avoid using large string fields for _id to prevent memory overload.
4. Combine $group with $sort and $project – Use $sort for ordering results and $project for refining output.

Conclusion

Overall, The $group command in MongoDB's aggregation framework allow users to perform complex data manipulations and analytics efficiently. By using its capabilities, developers and data analysts can derive actionable insights from diverse datasets, enhancing decision-making processes and operational efficiencies. By mastering the $group command, we can enhance our MongoDB data processing skills and build efficient data-driven applications.


Next Article
Aggregation in MongoDB

K

kumarsar29u2
Improve
Article Tags :
  • MongoDB
  • Databases

Similar Reads

  • MongoDB Aggregation $lookup
    MongoDB $lookup stage is a powerful feature within the Aggregation Framework that allows us to perform a left outer join between collections. This allows developers to combine related data from multiple collections within the same database which is highly useful for scenarios requiring relational-li
    6 min read
  • Python MongoDB - $group (aggregation)
    MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. In this article, we will see the use of $group in MongoDB using Python. $group operation In PyMongo, the Aggregate Method is
    3 min read
  • Aggregation in MongoDB
    Aggregation in MongoDB is a powerful framework that allows developers to perform complex data transformations, computations and analysis on collections of documents. By utilizing the aggregation pipeline, users can efficiently group, filter, sort, reshape, and perform calculations on data to generat
    7 min read
  • Aggregation Commands
    Aggregation commands in MongoDB are powerful tools within the aggregation pipeline framework that enable complex data processing and analysis. These commands allow operations such as grouping, sorting and filtering data by making them essential for generating reports, summarizing data and performing
    6 min read
  • MongoDB Aggregation $out
    MongoDB's aggregation framework offers powerful tools for data analysis and the $out stage for data processing and analysis, with the $out stage playing a crucial role in persistently storing the results of an aggregation pipeline. This feature is highly beneficial for efficient data analysis, repor
    5 min read
  • DynamoDB - Aggregation
    In today's data-driven world, the ability to intelligently transform big data into actionable insights is crucial for the success of business. DynamoDB, offered by Amazon, act as a versatile and scalable NoSQL database solution known for its flexibility and performance levels. Aggregation plays a fu
    7 min read
  • MongoDB Aggregation $first Operator
    MongoDB's aggregation framework offers a rich set of operators for data manipulation and analysis. One such operator is $first, which retrieves the first document from a group of documents. In this article, we will learn about the $first operator in MongoDB aggregation by covering its concepts and u
    4 min read
  • MongoDB Aggregation Pipeline $limit
    The MongoDB aggregation pipeline is a powerful tool for data processing and transformation, allowing users to perform efficient filtering, sorting, grouping, and reshaping of documents. Among its various stages, the $limit stage is essential for restricting the number of documents that flow through
    7 min read
  • Aggregation in MongoDB using Python
    MongoDB is free, open-source,cross-platform and document-oriented database management system(dbms). It is a NoSQL type of database. It store the data in BSON format on hard disk. BSON is binary form for representing simple data structure, associative array and various data types in MongoDB. NoSQL is
    2 min read
  • Pyspark - Aggregation on multiple columns
    In this article, we will discuss how to perform aggregation on multiple columns in Pyspark using Python. We can do this by using Groupby() function Let's create a dataframe for demonstration:[GFGTABS] Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pys
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences