Explain $sum: 1?

QuestionsQuestions8 SkillsProGroup MongoDB DataNov, 12 2025
0120

In MongoDB, when you see $sum: 1 within an aggregation pipeline, it is typically used in the context of the $group stage to count the number of documents in each group.

Explanation

  • $sum: This is an accumulator operator that calculates the sum of numeric values.
  • 1: When you use 1 as the value for $sum, it effectively counts each document that falls into the group because you are summing the value 1 for each document.

Example Usage

Here’s an example to illustrate how $sum: 1 works in an aggregation pipeline:

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

Result

In this example:

  • The documents in the orders collection are grouped by customerId.
  • The orderCount field will contain the total number of orders for each customer, as it sums 1 for each document in that group.

This is a common pattern used to count documents in MongoDB aggregation queries.

0 Comments

no data
Be the first to share your comment!