Windowed Aggregations on Time Series
Learners will use $setWindowFields with time-based window bounds to compute rolling averages and cumulative sums over sensor readings.
What Are Window Functions?
A window function computes a value for each document in a result set by looking at a surrounding range (the 'window') of documents — without collapsing them into a group the way $group does. Each input document produces exactly one output document, but the computed value reflects aggregation across the window. MongoDB added window functions via the $setWindowFields stage in version 5.0.
The $setWindowFields Stage
$setWindowFields is the aggregation stage that enables window functions in MongoDB. It accepts a partitionBy expression (similar to SQL's PARTITION BY), an output object defining new fields and their window operators, and a sortBy document that establishes the ordering within each partition. This combination makes it ideal for time series: partition by sensor, sort by timestamp, compute running totals or moving averages.
db.sensorReadings.aggregate([
{
$setWindowFields: {
partitionBy: '$sensorId', // one window per sensor
sortBy: { timestamp: 1 }, // ordered by time ascending
output: {
runningTotal: {
$sum: '$temperature',
window: { documents: ['unbounded', 'current'] }
}
}
}
}
])All lessons in this course
- Creating a Time Series Collection
- Inserting and Querying Time Series Data
- Windowed Aggregations on Time Series
- Automatic Data Expiration With expireAfterSeconds