How does $sum: 1 work?

QuestionsQuestions8 SkillsProGroup MongoDB DataNov, 12 2025
0122

The $sum: 1 operation in MongoDB's aggregation framework is used to count the number of documents in a group. Here's how it works:

Mechanism

  1. Grouping: When you use the $group stage in an aggregation pipeline, you specify a field (or fields) to group by. MongoDB will create a group for each unique value of the specified field.

  2. Counting Documents: By using $sum: 1, you instruct MongoDB to add 1 for each document that belongs to the group. Essentially, for every document that matches the grouping criteria, it increments the count by 1.

Example

Consider the following example:

db.orders.aggregate([
    {
        $group: {
            _id: "$customerId", // Group by customerId
            orderCount: { $sum: 1 } // Count the number of orders for each customer
        }
    }
])

Explanation of the Example

  • Input Documents: Suppose you have the following documents in the orders collection:
{ "customerId": "C1", "amount": 100 }
{ "customerId": "C1", "amount": 150 }
{ "customerId": "C2", "amount": 200 }
  • Grouping: The aggregation groups these documents by customerId. In this case, there are two groups: one for C1 and one for C2.

  • Counting: For each document in the group, $sum: 1 adds 1 to the orderCount. So:

    • For C1, there are 2 documents, so orderCount will be 2.
    • For C2, there is 1 document, so orderCount will be 1.

Result

The output of the aggregation would be:

{ "_id": "C1", "orderCount": 2 }
{ "_id": "C2", "orderCount": 1 }

Summary

In summary, $sum: 1 is a simple and effective way to count the number of documents in each group during an aggregation operation in MongoDB. It works by incrementing the count for each document that matches the grouping criteria.

0 Comments

no data
Be the first to share your comment!