- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $setWindowFields (aggregation)
$setWindowFields (aggregation)¶
On this page
Definition¶
-
$setWindowFields¶
New in version 5.0.
Performs operations on a specified span of documents in a collection, known as a window, and returns the results based on the chosen window operator.
For example, you can use the $setWindowFields stage to
output the:
- Difference in sales between two documents in a collection.
- Sales rankings.
- Cumulative sales totals.
- Analysis of complex time series information without exporting the data to an external database.
Syntax¶
The $setWindowFields stage syntax:
The $setWindowFields stage takes a document with these
fields:
| Field | Necessity | Description |
|---|---|---|
| partitionBy | Optional | Specifies an expression to group
the documents. In the |
| sortBy | Required for some operators (see Restrictions) | Specifies the field(s) to sort the documents by in the partition.
Uses the same syntax as the |
| output | Required | Specifies the field(s) to append to the documents in the output
returned by the A field can contain dots to
specify embedded document fields and array fields. The semantics
for the embedded document dotted notation in the
|
| window | Optional | Specifies the window boundaries and parameters. Window boundaries are inclusive. Default is an unbounded window, which includes all documents in the partition. |
| documents | Optional | A window where the lower and upper boundaries are specified relative to the position of the current document read from the collection. The window boundaries are specified using a two element array containing a lower and upper limit string or integer. Use:
|
| range | Optional | A window where the lower and upper boundaries are defined using a range of values based on the sortBy field in the current document. The window boundaries are specified using a two element array containing a lower and upper limit string or number. Use:
See Range Window Example. |
| unit | Optional | Specifies the units for time range window boundaries. Can be set to one of these strings:
If omitted, default numeric range window boundaries are used. |
See also
Behavior¶
The $setWindowFields stage appends new fields to existing
documents. You can include one or more $setWindowFields
stages in an aggregation operation.
Starting in MongoDB 5.3, you can use the $setWindowFields
stage with transactions and the
"snapshot" read concern.
Window Operators¶
These operators can be used with the $setWindowFields stage:
- Accumulator operators:
$addToSet,$avg,$bottom,$bottomN,$count,$covariancePop,$covarianceSamp,$derivative,$expMovingAvg,$firstN,$integral,$lastN,$max,$maxN,$min,$minN,$push,$stdDevSamp,$stdDevPop,$sum,$top,$topN.
- Gap filling operators:
$linearFilland$locf.
- Rank operators:
$denseRank,$documentNumber, and$rank.
Restrictions¶
Restrictions for the $setWindowFields stage:
- Starting in MongoDB 5.1 (and 5.0.4), the
$setWindowFieldsstage cannot be used:- Within transactions.
- With
"snapshot"read concern.
- sortBy is required for:
- Rank and order window operators.
- Bounded windows (either a documents window or a range window).
$linearFilloperator.
- Range windows require all sortBy values to be numbers.
- Time range windows require all sortBy values to be dates.
- Range and time range windows can only contain one sortBy field and the sort must be ascending.
- You cannot specify both a documents window and a range window.
- These operators use an implicit window and return an error if you specify a window option:
- For range windows, only numbers in
the specified range are included in the window. Missing, undefined,
and
nullvalues are excluded. - For time range windows:
- Only date and time types are included in the window.
- Numeric boundary values must be integers. For example, you can use 2 hours as a boundary but you cannot use 1.5 hours.
- For empty windows or windows with incompatible values (for example,
using
$sumon strings), the returned value depends on the operator:
Examples¶
Create a cakeSales collection that contains cake sales in the states
of California (CA) and Washington (WA):
The following examples use the cakeSales collection.
Documents Window Examples¶
Use Documents Window to Obtain Cumulative Quantity for Each State¶
This example uses a documents window
in $setWindowFields to output the cumulative cake sales
quantity for each state:
In the example:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.output:Sets the
cumulativeQuantityForStatefield to the cumulativequantityfor eachstate, which increases by successive additions to the previous value in the partition.Calculates the cumulative
quantityusing the$sumoperator run in a documents window.The window contains documents between an
unboundedlower limit and thecurrentdocument. This means$sumreturns the cumulativequantityfor the documents between the beginning of the partition and the current document.
In this example output, the cumulative quantity for CA and
WA is shown in the cumulativeQuantityForState field:
Use Documents Window to Obtain Cumulative Quantity for Each Year¶
This example uses a documents window
in $setWindowFields to output the cumulative cake sales
quantity for each $year in orderDate:
In the example:
partitionBy: { $year: "$orderDate" }partitions the documents in the collection by$yearinorderDate. There are are partitions for2019,2020, and2021.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.output:Sets the
cumulativeQuantityForYearfield to the cumulativequantityfor each year, which increases by successive additions to the previous value in the partition.Calculates the cumulative
quantityusing the$sumoperator run in a documents window.The window contains documents between an
unboundedlower limit and thecurrentdocument. This means$sumreturns the cumulativequantityfor the documents between the beginning of the partition and the current document.
In this example output, the cumulative quantity for each year is
shown in the cumulativeQuantityForYear field:
Use Documents Window to Obtain Moving Average Quantity for Each Year¶
This example uses a documents window
in $setWindowFields to output the moving average
for the cake sales quantity:
In the example:
partitionBy: "$orderDate"partitions the documents in the collection by$yearinorderDate. There are are partitions for2019,2020, and2021.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.output:Sets the
averageQuantityfield to the moving averagequantityfor each year.Calculates the moving average
quantityusing the$avgoperator run in a documents window.The window contains documents between
-1and0. This means$avgreturns the moving averagequantitybetween the document before the current document (-1) and the current document (0) in the partition.
In this example output, the moving average quantity is shown in the
averageQuantity field:
Use Documents Window to Obtain Cumulative and Maximum Quantity for Each Year¶
This example uses a documents window
in $setWindowFields to output the cumulative and maximum
cake sales quantity values for each $year in
orderDate:
In the example:
partitionBy: "$orderDate"partitions the documents in the collection by$yearinorderDate. There are are partitions for2019,2020, and2021.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.output:Sets the
cumulativeQuantityForYearfield to the cumulativequantityfor each year.Calculates the cumulative
quantityusing the$sumoperator run in a documents window.The window contains documents between an
unboundedlower limit and thecurrentdocument. This means$sumreturns the cumulative quantity for the documents between the beginning of the partition and the current document.Sets the
maximumQuantityForYearfield to the maximumquantityfor each year.Calculates the maximum
quantityof all the documents using the$maxoperator run in a documents window.The window contains documents between an
unboundedlower andupperlimit. This means$maxreturns the maximum quantity for the documents in the partition.
In this example output, the cumulative quantity is shown in the
cumulativeQuantityForYear field and the maximum quantity is
shown in the maximumQuantityForYear field:
Range Window Example¶
This example uses a range window in
$setWindowFields to return the sum of the quantity
values of cakes sold for orders within plus or minus 10 dollars of the
current document’s price value:
In the example:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { price: 1 }sorts the documents in each partition bypricein ascending order (1), so the lowestpriceis first.outputsets thequantityFromSimilarOrdersfield to the sum of thequantityvalues from the documents in a range window.
In this example output, the sum of the quantity values for documents
in the window is shown in the quantityFromSimilarOrders field:
Time Range Window Examples¶
Use a Time Range Window with a Positive Upper Bound¶
The following example uses a window with
a positive upper bound time range unit in
$setWindowFields. The pipeline outputs an array of
orderDate values for each state that match the specified time
range.
In the example:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.output:- The window contains documents
between an
unboundedlower limit and an upper limit set to10(10 months after the current document’sorderDatevalue) using a time range unit. $pushreturns the array oforderDatevalues for the documents between the beginning of the partition and the documents withorderDatevalues inclusively in a range of the current document’sorderDatevalue plus10months.
In this example output, the array of orderDate values for CA and
WA is shown in the recentOrders field:
Use a Time Range Window with a Negative Upper Bound¶
The following example uses a window with
a negative upper bound time range unit in
$setWindowFields. The pipeline outputs an array of
orderDate values for each state that match the specified time
range.
In the example:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.output:- The window contains documents
between an
unboundedlower limit and an upper limit set to-10(10 months before the current document’sorderDatevalue) using a time range unit. $pushreturns the array oforderDatevalues for the documents between the beginning of the partition and the documents withorderDatevalues inclusively in a range of the current document’sorderDatevalue minus10months.
In this example output, the array of orderDate values for CA and
WA is shown in the recentOrders field:
See also
For an additional example about IOT Power Consumption, see the Practical MongoDB Aggregations e-book.