- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $expMovingAvg (aggregation)
$expMovingAvg (aggregation)¶
On this page
Definition¶
New in version 5.0.
-
$expMovingAvg¶
Returns the exponential moving average of numeric expressions applied to documents in a partition defined in the
$setWindowFields stage.
$expMovingAvg is only available in the
$setWindowFields stage.
$expMovingAvg syntax:
$expMovingAvg takes a document with these fields:
| Field | Description |
|---|---|
| input | Specifies the expression to evaluate. Non-numeric expressions are ignored. |
| N | An You must specify either N or alpha. You cannot specify both. The |
| alpha | A You must specify either N or alpha. You cannot specify both. The |
Behavior¶
You must specify either N or alpha. You cannot specify both.
$expMovingAvg ignores non-numeric values, null values, and
missing fields.
Examples¶
Create a stockPrices collection that contains prices for stocks
named "ABC" and "DEF":
Exponential Moving Average Using N¶
This example uses $expMovingAvg in the
$setWindowFields stage to output the exponential moving
average for the stock prices weighted for two historical documents (two
days for the example documents) using N set to
2:
In the example:
partitionBy: "$stock"partitions the documents in the collection bystock. There are partitions for"ABC"and"DEF".sortBy: { date: 1 }sorts the documents in each partition bydatein ascending order (1), so the earliestdateis first.outputreturns the exponential moving average for the stockpricefield with N set to2:- In the input documents, there is one document for each day
and the documents are ordered by
date. Therefore, with N is set to2, thepricein the current document and thepricein the previous document, if available, are allocated the highest weight in the exponential moving average formula. - The exponential moving average for the
pricefield is stored in a new field calledexpMovingAvgForStocks, as shown in the following results.
- In the input documents, there is one document for each day
and the documents are ordered by
Exponential Moving Average Using alpha¶
This example uses $expMovingAvg in the
$setWindowFields stage to output the exponential moving
average for the stock prices using alpha set
to 0.75:
In the example:
partitionBy: "$stock"partitions the documents in the collection bystock. There are partitions for"ABC"and"DEF".sortBy: { date: 1 }sorts the documents in each partition bydatein ascending order (1), so the earliestdateis first.outputsets the exponential moving average for the stock prices in a new field calledexpMovingAvgForStock, as shown in the following results. The value for alpha is set to0.75in the exponential moving average formula.