Learning MongoDB: Grouping and Counting Documents


When managing and analyzing voluminous datasets within a NoSQL environment like MongoDB, the ability to efficiently aggregate and summarize information becomes absolutely fundamental. This comprehensive guide is dedicated to mastering a core operation: grouping documents based on a chosen field and subsequently calculating the total count of documents contained within each resulting group. This powerful analytical task is executed seamlessly using MongoDB’s robust toolset, specifically the Aggregation Pipeline.

Understanding the MongoDB Aggregation Pipeline

Unlike traditional SQL databases that rely on the declarative GROUP BY clause, MongoDB employs the concept of the Aggregation Pipeline. This pipeline is a multi-stage framework designed to transform documents through various processing steps, ultimately yielding calculated and aggregated results. Conceptually, the stages of the pipeline operate much like command chains in a Unix shell, where the output of one stage is automatically piped as the input to the next, allowing for highly complex data transformations.

To successfully achieve both grouping and counting operations, we primarily utilize the $group stage. This crucial stage is responsible for collecting all input documents that share an identical value for a specified unique identifier—known as the grouping key. Once documents are collected into groups, the stage applies predefined **accumulator expressions** to those grouped documents; in this specific context, our goal is simply to count them.

The overall process is initiated by calling the **db.collection.aggregate()** method. This method accepts an array as its primary argument, which contains the ordered sequence of necessary aggregation stages. This structured, declarative approach guarantees exceptional flexibility and robust performance, even when handling massive datasets and executing intricate data manipulations.

The Core Syntax: Grouping and Counting

The fundamental approach for executing a group-by-and-count operation in MongoDB is remarkably concise, requiring only a single, well-defined stage within the aggregation array. This stage mandates the use of the $group operator in conjunction with the powerful accumulator operator, $sum.

The standard syntax provided below illustrates how documents are tallied based on the unique values present within a designated field of your collection. Crucially, it establishes a new output field, conventionally named count, which stores the calculated tally corresponding to each distinct _id (the grouping key) defined by the chosen field.

db.collection.aggregate([
    {$group : {_id:"$field_name", count:{$sum:1}}}
])

It is essential to understand the specific function of each component within this aggregation stage:

  • The _id field within the $group stage dictates the **grouping key**. By prefixing the field_name with a dollar sign ($field_name), we instruct MongoDB to use the actual value of that document field as the unique key by which all documents will be consolidated.
  • The count field serves as the descriptive name for the new field that will house the final aggregated result (the document tally).
  • The expression {$sum: 1} is the designated **accumulator**. The $sum operator computes the total sum of the values it processes. By assigning a constant value of 1 to every single document that enters this stage, we effectively ensure a precise count of all documents within that specific group.

Setting Up the Example Dataset

To illustrate these powerful aggregation techniques in a practical manner, we will utilize a sample collection named teams. This collection models basketball player data, with each document detailing a player’s team affiliation, their specific playing position, and the total points they scored.

We will use the following five sample documents as the foundation for our subsequent aggregation queries. These examples provide clear inputs that demonstrate how varying field values, such as position, will be effectively grouped and tallied in the practical examples that follow:

db.teams.insertOne({team: "Mavs", position: "Guard", points: 31})
db.teams.insertOne({team: "Spurs", position: "Guard", points: 22})
db.teams.insertOne({team: "Rockets", position: "Center", points: 19})
db.teams.insertOne({team: "Warriors", position: "Forward", points: 26})
db.teams.insertOne({team: "Cavs", position: "Guard", points: 33})

Our immediate analytical objective is straightforward: to accurately determine the total number of players associated with each distinct playing position (Guard, Center, Forward) within this sample dataset, leveraging the power and efficiency of the Aggregation Pipeline.

Example 1: Basic Grouping and Counting

In this inaugural example, we apply the foundational syntax previously discussed directly to the teams collection. Our explicit goal is to categorize the documents based exclusively on the value of the position field and then tabulate exactly how many documents fall into each unique position category.

The query below utilizes $position as the designated grouping key (_id). All documents possessing the same position value will be effectively bundled together, allowing the $sum accumulator to precisely tally the total number of documents (players) within that specific bundle.

db.teams.aggregate([
    {$group : {_id:"$position", count:{$sum:1}}}
])

Executing this aggregation query yields the following structured results, powerfully demonstrating the successful grouping and counting of player positions:

{ _id: 'Forward', count: 1 }
{ _id: 'Guard', count: 3 }
{ _id: 'Center', count: 1 }

These results provide a succinct and clear summary of the data distribution, confirming the following breakdown of player positions in our collection:

  • The position **Forward** occurs exactly 1 time.
  • The position **Guard** occurs a total of 3 times.
  • The position **Center** occurs exactly 1 time.

Example 2: Grouping, Counting, and Sorting Results

While the first example successfully calculated the counts for each group, it is crucial to understand that the order of the resulting documents is not guaranteed by default. Data analysts frequently prefer to view results sorted, commonly displaying the most frequent categories first. To implement this required ordering, we must introduce a subsequent stage into the Aggregation Pipeline: the $sort operator.

The $sort stage must be strategically placed immediately following the $group stage. This placement ensures the documents are fully aggregated and counted before the ordering process begins. We will sort the output documents based on the values of the newly created count field.

Sorting in Ascending Order

To sort the results in **ascending order** (ranking from the lowest count to the highest count), we pass the integer value 1 to the count field definition within the $sort stage:

db.teams.aggregate([
    {$group : {_id:"$position", count:{$sum:1}}},
    {$sort: {count:1}} 
])

The execution of this pipeline returns the following, perfectly ordered by count, starting from the least frequent positions:

{ _id: 'Forward', count: 1 }
{ _id: 'Center', count: 1 }
{ _id: 'Guard', count: 3 }

Sorting in Descending Order

Conversely, if the requirement is to immediately highlight the categories with the greatest frequency, we must sort the results in **descending order**. This is achieved by setting the sort value to -1 for the count field. This methodology is typically preferred for exploratory data analysis, as it quickly identifies the dominant categories within any given dataset.

db.teams.aggregate([
    {$group : {_id:"$position", count:{$sum:1}}},
    {$sort: {count:-1}} 
])

The resulting output clearly prioritizes the position with the highest count (Guard) by placing it at the very top of the result set:

{ _id: 'Guard', count: 3 }
{ _id: 'Forward', count: 1 }
{ _id: 'Center', count: 1 }

Note: The true power of the Aggregation Pipeline derives from its inherent flexibility. Once the foundational $group operation is mastered, developers can easily integrate numerous other stages—such as $match (for precise filtering), $project (for reshaping and limiting output documents), or $limit (for efficient pagination)—to construct highly tailored analytical workflows.

Leveraging Advanced Accumulators

While this tutorial focused exclusively on counting documents per group using the expression {$sum: 1}, the $group stage is engineered to handle significantly more complex analytical tasks. Developers can utilize a wide array of other **accumulator operators**, including $avg, $max, $min, and $push, to calculate statistical measures or collect specific array elements within each defined group.

For example, if the objective were to calculate the **average points scored per position** instead of merely counting the players, the accumulator would be modified. You would switch to using the $avg operator applied directly to the $points field, replacing the standard $sum: 1 expression. A deep understanding of the versatility of these accumulator operators is the key to unlocking the full analytical potential of MongoDB’s aggregation framework.

For developers seeking comprehensive and authoritative details on all available aggregation stages and operators, consulting the official $sum and $sort documentation pages is highly recommended for advanced use cases.

Additional Resources

The following tutorials explain how to perform other essential operations in MongoDB, empowering you to build a comprehensive and effective skill set for advanced data manipulation and robust analysis:

Cite this article

Mohammed looti (2025). Learning MongoDB: Grouping and Counting Documents. PSYCHOLOGICAL STATISTICS. Retrieved from https://statistics.arabpsychology.com/mongodb-group-by-and-count/

Mohammed looti. "Learning MongoDB: Grouping and Counting Documents." PSYCHOLOGICAL STATISTICS, 1 Nov. 2025, https://statistics.arabpsychology.com/mongodb-group-by-and-count/.

Mohammed looti. "Learning MongoDB: Grouping and Counting Documents." PSYCHOLOGICAL STATISTICS, 2025. https://statistics.arabpsychology.com/mongodb-group-by-and-count/.

Mohammed looti (2025) 'Learning MongoDB: Grouping and Counting Documents', PSYCHOLOGICAL STATISTICS. Available at: https://statistics.arabpsychology.com/mongodb-group-by-and-count/.

[1] Mohammed looti, "Learning MongoDB: Grouping and Counting Documents," PSYCHOLOGICAL STATISTICS, vol. X, no. Y, ص Z-Z, November, 2025.

Mohammed looti. Learning MongoDB: Grouping and Counting Documents. PSYCHOLOGICAL STATISTICS. 2025;vol(issue):pages.

Download Post (.PDF)
Scroll to Top