- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $shift (aggregation)
$shift (aggregation)¶
On this page
Definition¶
New in version 5.0.
-
$shift¶
Returns the value from an expression
applied to a document in a specified position relative to the current
document in the $setWindowFields stage partition.
The $setWindowFields stage sortBy field value determines the document order. For
more information on how MongoDB compares fields with different types,
see BSON comparison order.
$shift is only available in the $setWindowFields
stage.
$shift syntax:
$shift takes a document with these fields:
| Field | Description |
|---|---|
| output | Specifies an expression to evaluate and return in the output. |
| by | Specifies an For example:
|
| default | Specifies an optional default expression to evaluate if the document position
is outside of the implicit The default expression must evaluate to a constant value. If you do not specify a default
expression, |
Behavior¶
$shift returns an error if you specify a window in the $setWindowFields stage.
Examples¶
Create a cakeSales collection that contains cake sales in the states
of California (CA) and Washington (WA):
The cakeSales collection is used in the following examples.
Shift Using a Positive Integer¶
This example uses $shift in the $setWindowFields
stage to output the quantity of the cake sales from each document
following the current document for each state:
In the example:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { quantity: -1 }sorts the documents in each partition byquantityin descending order (-1), so the highestquantityis first.outputaftersortBy:- Sets the
shiftQuantityForStatefield to thequantityvalue from the documents in eachstate. - Uses
$shiftto return thequantityvalue from the document that follows the current document in the output.
- Sets the
In this example output, the shifted quantity value is shown in the
shiftQuantityForState field for each returned document:
Shift Using a Negative Integer¶
This example uses $shift in the $setWindowFields
stage to output the quantity of the cake sales from each document
before the current document for each state:
In the example:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { quantity: -1 }sorts the documents in each partition byquantityin descending order (-1), so the highestquantityis first.outputaftersortBy:- Sets the
shiftQuantityForStatefield to thequantityvalue from the documents in eachstate. - Uses
$shiftto return thequantityvalue from the document before the current document in the output.
- Sets the
In this example output, the shifted quantity value is shown in the
shiftQuantityForState field for each returned document: