$expMovingAvg
Calculates the exponential moving average of field values, giving higher weight to recent documents in the calculation for trend analysis.
Syntax
{ $expMovingAvg: { input: <field>, N: <number> } }
Parameters
input
objectrequiredField whose values are used to calculate the exponential moving average
N
numberNumber of previous documents with highest weight in calculation
alpha
numberDecay rate parameter, higher values give less weight to previous documents
Examples
Calculate exponential moving average of total sales
Compute exponential moving average with highest weight on 2 recent documents
Query:
db.stores.aggregate([{ $match: { "company": { $in: ["First Up Consultants"] } } }, { $setWindowFields: { "partitionBy": "$company", "sortBy": { "storeOpeningDate": 1 }, "output": { "expMovingAvgForSales": { "$expMovingAvg": { "input": "$sales.totalSales", "N": 2 } } } } }])
Output:
Stores with exponential moving average of sales using 2-document weight
Calculate exponential moving average using alpha parameter
Use decay rate parameter for exponential moving average calculation
Query:
db.stores.aggregate([{ $match: { "company": { $in: ["First Up Consultants"] } } }, { $setWindowFields: { "partitionBy": "$company", "sortBy": { "storeOpeningDate": 1 }, "output": { "expMovingAvgForSales": { "$expMovingAvg": { "input": "$sales.totalSales", "alpha": 0.75 } } } } }])
Output:
Stores with exponential moving average using 0.75 alpha decay rate