$sum, $avg, $min, $max: 숫자 집계
학습자는 $group 안에서 합계, 평균, 최솟값, 최댓값을 계산하고, 이러한 누산기를 $project의 표현식 연산자로도 사용합니다.
$sum, $avg, $min, $max: 숫자 집계은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Numeric Accumulators in $group
MongoDB's $group stage uses accumulators to compute aggregate values from grouped documents. The most fundamental numeric accumulators are $sum, $avg, $min, and $max. Each accumulator processes all documents in a group and produces a single output value. These operators form the backbone of analytics pipelines.
Using $sum to Count and Total
The $sum accumulator has two common uses: counting documents by passing a literal value like 1, and summing a field by referencing a numeric field. When a field is missing or null, $sum treats it as zero. This makes it safe to use on optional numeric fields without extra null-checks.
db.orders.aggregate([
{
$group: {
_id: '$status',
orderCount: { $sum: 1 },
totalRevenue: { $sum: '$amount' }
}
}
])Computing Averages With $avg
The $avg accumulator computes the arithmetic mean of a numeric field across all documents in a group. It automatically ignores documents where the field is missing or null, computing the average only over valid values. This is useful for metrics like average order value or average rating per product.
db.reviews.aggregate([
{
$group: {
_id: '$productId',
averageRating: { $avg: '$rating' },
reviewCount: { $sum: 1 }
}
},
{ $sort: { averageRating: -1 } }
])Finding Extremes With $min and $max
$min and $max return the smallest and largest values in a group respectively. They work on any comparable type—numbers, dates, and strings. A common use case is finding the first and last event times within a session, or the cheapest and most expensive product in a category. They ignore null and missing values.
db.sessions.aggregate([
{
$group: {
_id: '$userId',
firstLogin: { $min: '$timestamp' },
lastLogin: { $max: '$timestamp' },
minSessionDuration: { $min: '$durationSeconds' },
maxSessionDuration: { $max: '$durationSeconds' }
}
}
])Grouping by Null for Global Totals
To compute a single aggregate over the entire collection, set the _id to null. This groups all documents into one bucket. This technique is how you calculate totals, overall averages, and global extremes without segmenting data. Think of it as the MongoDB equivalent of a SQL SELECT SUM(*) FROM orders with no GROUP BY clause.
db.orders.aggregate([
{
$group: {
_id: null,
totalOrders: { $sum: 1 },
grandTotal: { $sum: '$amount' },
averageOrder: { $avg: '$amount' },
minOrder: { $min: '$amount' },
maxOrder: { $max: '$amount' }
}
}
])Using These Accumulators in $project
A lesser-known feature is that $sum, $avg, $min, and $max can also be used as expression operators in $project—not just in $group. In this context, they operate on an array within a single document rather than across multiple documents. This allows you to compute the sum of elements in an embedded array field without a $group stage.
db.carts.aggregate([
{
$project: {
userId: 1,
// Sum elements inside the items array
cartTotal: { $sum: '$items.price' },
maxItemPrice: { $max: '$items.price' },
avgItemPrice: { $avg: '$items.price' }
}
}
])Nested Expressions Inside Accumulators
Accumulators accept any valid expression, not just field references. You can use arithmetic operators, conditional expressions, and even $cond inside an accumulator. This lets you implement conditional sums like 'sum only completed orders' or 'count only high-value transactions' in a single pipeline stage.
db.orders.aggregate([
{
$group: {
_id: '$customerId',
// Only sum orders that are 'completed'
completedRevenue: {
$sum: {
$cond: [
{ $eq: ['$status', 'completed'] },
'$amount',
0
]
}
}
}
}
])Multi-Level Grouping Pipelines
You can chain multiple $group stages to compute multi-level aggregations. A first group computes per-day totals, and a second group computes monthly averages from those daily totals. This pattern is cleaner than doing everything in one stage and makes the pipeline logic easier to reason about.
db.sales.aggregate([
// First group: totals per day
{
$group: {
_id: { year: { $year: '$date' }, month: { $month: '$date' }, day: { $dayOfMonth: '$date' } },
dailyTotal: { $sum: '$amount' }
}
},
// Second group: average daily total per month
{
$group: {
_id: { year: '$_id.year', month: '$_id.month' },
avgDailyRevenue: { $avg: '$dailyTotal' },
totalMonthRevenue: { $sum: '$dailyTotal' }
}
}
])Filtering Before Grouping With $match
Always place a $match stage before $group to filter down to the relevant documents first. This reduces the number of documents the grouping stage must process and, crucially, allows MongoDB to use an index to satisfy the filter. A $match after $group filters group results, which is also useful but does not benefit from indexes.
db.orders.aggregate([
// Filter first — MongoDB can use an index on createdAt
{
$match: {
createdAt: { $gte: new Date('2024-01-01') },
status: 'completed'
}
},
{
$group: {
_id: '$region',
totalRevenue: { $sum: '$amount' },
avgRevenue: { $avg: '$amount' }
}
},
{ $sort: { totalRevenue: -1 } }
])Handling Missing and Null Values
When a field referenced in $sum or $avg is missing or null, the behavior differs slightly. $sum treats missing/null as zero, so all documents contribute to the count. $avg and $min/$max ignore missing/null values entirely—they do not factor into the computation. Understanding this distinction prevents subtle bugs in your analytics queries.
// Consider documents where some lack a 'discount' field
// $sum: missing = 0, so it counts in the total
// $avg: missing fields are ignored, avg is over existing values only
db.orders.aggregate([
{
$group: {
_id: '$category',
totalDiscount: { $sum: '$discount' }, // missing = 0
avgDiscount: { $avg: '$discount' } // missing = ignored
}
}
])Practical Example: Sales Dashboard
Combining $sum, $avg, $min, and $max in one $group stage is a common pattern for dashboard metrics. A single aggregation pipeline can return everything needed to populate a summary card: total orders, revenue, average order value, and the range of order sizes. This avoids multiple round-trips to the database.
db.orders.aggregate([
{ $match: { status: 'completed' } },
{
$group: {
_id: '$category',
totalOrders: { $sum: 1 },
totalRevenue: { $sum: '$amount' },
avgOrderValue: { $avg: '$amount' },
smallestOrder: { $min: '$amount' },
largestOrder: { $max: '$amount' }
}
},
{ $sort: { totalRevenue: -1 } },
{ $limit: 10 }
])Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: $sum totals values and counts documents (missing = 0), $avg/$min/$max ignore missing or null fields, and these accumulators work in both $group (across documents) and $project (within an array). Next up we explore $push and $addToSet for building arrays within groups.
AI 튜터와 함께 JavaScript을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 30
- 레슨
- 120
자주 묻는 질문
“$sum, $avg, $min, $max: 숫자 집계” 강의는 무료인가요?
네 — “$sum, $avg, $min, $max: 숫자 집계” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“$sum, $avg, $min, $max: 숫자 집계”에서 뭘 배우나요?
학습자는 $group 안에서 합계, 평균, 최솟값, 최댓값을 계산하고, 이러한 누산기를 $project의 표현식 연산자로도 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“$sum, $avg, $min, $max: 숫자 집계” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- $sum, $avg, $min, $max: 숫자 집계
- $push와 $addToSet: 그룹에서 배열 만들기
- $first, $last 및 $top/$bottom 누산기
- $setWindowFields를 사용한 윈도 함수