- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $derivative (aggregation)
$derivative (aggregation)¶
On this page
Definition¶
New in version 5.0.
-
$derivative
¶
Returns the average rate of change within the specified window, which is calculated using the:
- First and last documents in the
$setWindowFields
stage window. - Numerator, which is set to the result of subtracting the numeric expression value for the first document from the expression value for the last document.
- Denominator, which is set to the result of subtracting the sortBy field value for the first document from the sortBy field value for the last document.
$derivative
is only available in the
$setWindowFields
stage. You must specify a window in the $setWindowFields
stage when
using $derivative
.
$derivative
syntax:
$derivative
takes a document with these fields:
Field | Description |
---|---|
input | Specifies the expression to evaluate. The expression must evaluate to a number. |
unit | A
If the sortBy field is not a date, you
must omit a |
Behavior¶
You must specify a window in the
$setWindowFields
stage when using $derivative
.
Example¶
Create a deliveryFleet
collection that contains odometer
readings for delivery trucks recorded at 30 second intervals:
This example uses $derivative
in the
$setWindowFields
stage to obtain the average speed in miles
per hour for each truck, and the $match
stage to filter the
results to trucks whose speed exceeded 50 miles per hour:
In the example:
- The
$setWindowFields
stage obtains the average speed in miles per hour for each truck:partitionBy: "$truckID"
partitions the documents in the collection bytruckID
.sortBy: { timeStamp: 1 }
sorts the documents in each partition bytimeStamp
in ascending order (1
), so the earliest odometer reading is first.output
sets themiles
derivative value in a new field calledtruckAverageSpeed
using$derivative
that is run in a range window.- The input expression is set to
"$miles"
, which is used in the numerator for the derivative calculation. - The
$derivative
unit is set to"hour"
for thetimeStamp
field, which is used in the denominator for the derivative calculation. - The window contains the
range between a lower limit of
-30
seconds (the previous 30 seconds from the current document in the output) and0
seconds (matches the current document’stimeStamp
value in the output). This means$derivative
returns the average speed for each truck in miles per hour in the 30 second window.
- The input expression is set to
- The
$match
stage uses the greater than operator$gt
to filter the results to trucks whose speed exceeded 50 miles per hour.
In the following example output, the speed for truck 1 is shown in the
truckAverageSpeed
field. The speed for truck 2 is not shown because
truck 2 did not exceed 50 miles per hour.