$setWindowFields를 사용한 윈도 함수
학습자는 $setWindowFields 단계를 사용해 정렬된 파티션에서 누적 합계, 순위, 이동 평균을 계산합니다.
$setWindowFields를 사용한 윈도 함수은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Are Window Functions?
Window functions compute values over a set of documents related to the current document—a 'window'—without collapsing them into a single group like $group does. They originated in SQL (SQL:2003) and were added to MongoDB in version 5.0 through the $setWindowFields pipeline stage. Common use cases include running totals, moving averages, rank, and cumulative metrics.
The $setWindowFields Stage Structure
The $setWindowFields stage has three main configuration keys: partitionBy defines how to divide documents into independent windows (like GROUP BY in SQL), sortBy orders documents within each partition, and output specifies the new fields to compute along with their window operator and window bounds.
db.dailySales.aggregate([
{
$setWindowFields: {
partitionBy: '$region', // separate window per region
sortBy: { saleDate: 1 }, // order by date within each region
output: {
runningTotal: {
$sum: '$amount',
window: { documents: ['unbounded', 'current'] }
}
}
}
}
])Document-Based Window Bounds
Window bounds define which documents contribute to the computation for each row. Document-based bounds use the documents key with a two-element array: the start position and end position relative to the current document. 'unbounded' means 'from the beginning (or to the end)', 'current' means the current document, and numeric offsets like -1 mean 'one document before'. Common patterns: ['unbounded', 'current'] for a running total, [-1, 1] for a 3-document moving window.
// Running total: all documents from the start up to the current row
window: { documents: ['unbounded', 'current'] }
// 3-document moving window: previous, current, and next document
window: { documents: [-1, 1] }
// Cumulative (all documents from start to end)
window: { documents: ['unbounded', 'unbounded'] }Range-Based Window Bounds
Range-based bounds define the window using value ranges on the sort key rather than document offsets. This is especially useful for time-series data where you want 'the last 7 days' rather than 'the last 7 documents'. Use the range key with a unit for date fields. This correctly handles gaps in data where days might be missing.
db.temperatures.aggregate([
{
$setWindowFields: {
partitionBy: '$station',
sortBy: { readingDate: 1 },
output: {
sevenDayAvgTemp: {
$avg: '$temperature',
window: {
range: [-6, 0], // 6 days before up to current day
unit: 'day'
}
}
}
}
}
])Computing Running Totals
A running total (cumulative sum) is computed by setting the window to span from the first document in the partition to the current document. As MongoDB processes each document in sort order, it adds that document's value to all previous values. This produces a monotonically increasing total per partition, useful for cumulative revenue or progressive download counts.
db.transactions.aggregate([
{
$setWindowFields: {
partitionBy: '$accountId',
sortBy: { date: 1 },
output: {
runningBalance: {
$sum: '$amount',
window: { documents: ['unbounded', 'current'] }
}
}
}
},
{ $project: { accountId: 1, date: 1, amount: 1, runningBalance: 1 } }
])Moving Averages for Smoothing Data
A moving average smooths out short-term fluctuations in time-series data to reveal underlying trends. Configure the window to span a fixed number of periods in both directions (or only backwards for a 'trailing' average). Moving averages are common in financial charts, performance monitoring dashboards, and IoT sensor analysis.
db.stockPrices.aggregate([
{
$setWindowFields: {
partitionBy: '$ticker',
sortBy: { date: 1 },
output: {
movingAvg5Day: {
$avg: '$closePrice',
window: { documents: [-4, 0] } // current + 4 previous = 5 day average
},
movingAvg10Day: {
$avg: '$closePrice',
window: { documents: [-9, 0] } // 10-day trailing average
}
}
}
}
])Ranking With $rank and $denseRank
The $rank operator assigns a rank number to each document within its partition based on the sort order. Tied documents receive the same rank, and the next rank skips accordingly (1, 2, 2, 4). $denseRank assigns consecutive ranks without gaps for ties (1, 2, 2, 3). Neither takes a window specification—they always rank across the full partition.
db.leaderboard.aggregate([
{
$setWindowFields: {
partitionBy: '$gameId',
sortBy: { score: -1 }, // highest score = rank 1
output: {
rank: { $rank: {} },
denseRank: { $denseRank: {} }
}
}
},
{ $match: { rank: { $lte: 10 } } } // top 10 per game
])$documentNumber: Row Numbering Within Partition
$documentNumber assigns a sequential integer starting from 1 to each document within its partition, in sort order. Unlike $rank, it never repeats numbers—every document gets a unique number. This is useful for pagination, sequence numbering, or when you need to identify which row within a partition a document occupies.
db.orders.aggregate([
{
$setWindowFields: {
partitionBy: '$customerId',
sortBy: { orderDate: 1 },
output: {
orderSequence: { $documentNumber: {} } // 1st order, 2nd order, etc.
}
}
},
// Find customers' 3rd orders
{ $match: { orderSequence: 3 } }
])$shift: Accessing Adjacent Documents
$shift returns the value of an expression from a document at a specified offset relative to the current document within the partition. Use by: -1 to access the previous document's value (e.g., yesterday's price), by: 1 for the next document, and specify a default for when the offset falls outside the partition boundary.
db.dailyMetrics.aggregate([
{
$setWindowFields: {
partitionBy: '$metricName',
sortBy: { date: 1 },
output: {
previousValue: {
$shift: {
output: '$value',
by: -1,
default: null
}
},
// Compute day-over-day change using $shift
dayOverDayChange: {
$subtract: [
'$value',
{ $shift: { output: '$value', by: -1, default: '$value' } }
]
}
}
}
}
])Performance and Index Usage
$setWindowFields benefits from indexes on the partition and sort fields. An index that covers both the partition key and the sort key allows MongoDB to efficiently retrieve each partition's documents in sorted order without a full collection scan. Without an index, MongoDB must sort in-memory (up to allowDiskUse limits). For large collections, ensure indexes align with your window functions' partition and sort specifications.
// For this $setWindowFields:
// partitionBy: '$accountId', sortBy: { date: 1 }
// Create a compound index:
db.transactions.createIndex({ accountId: 1, date: 1 })
// MongoDB can now efficiently scan per-partition in date orderPractical Example: Sales Performance Report
A real-world sales report might need each salesperson's transactions enriched with their running total, their rank within their team, and the team cumulative total—all computed in a single pipeline without multiple joins or application-side computation. This is exactly the kind of analytical query $setWindowFields was built for.
db.sales.aggregate([
{
$setWindowFields: {
partitionBy: '$teamId',
sortBy: { amount: -1 },
output: {
rankInTeam: { $rank: {} },
runningTeamTotal: {
$sum: '$amount',
window: { documents: ['unbounded', 'current'] }
},
teamTotal: {
$sum: '$amount',
window: { documents: ['unbounded', 'unbounded'] }
}
}
}
}
])Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: $setWindowFields computes values over a sliding window of related documents without collapsing them like $group, document-based and range-based window bounds control which documents contribute to each computation, and operators like $rank, $denseRank, $documentNumber, and $shift enable ranking, numbering, and cross-row comparisons. Next up we explore ACID guarantees in MongoDB's distributed document store.
자주 묻는 질문
“$setWindowFields를 사용한 윈도 함수” 강의는 무료인가요?
네 — “$setWindowFields를 사용한 윈도 함수” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“$setWindowFields를 사용한 윈도 함수”에서 뭘 배우나요?
학습자는 $setWindowFields 단계를 사용해 정렬된 파티션에서 누적 합계, 순위, 이동 평균을 계산합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“$setWindowFields를 사용한 윈도 함수” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- $sum, $avg, $min, $max: 숫자 집계
- $push와 $addToSet: 그룹에서 배열 만들기
- $first, $last 및 $top/$bottom 누산기
- $setWindowFields를 사용한 윈도 함수