Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving averages using MongoDB's aggregation framework

Given that you have a collection of documents with either a date or period (2013-01) property, what's the best way to compute moving average statistics (say 3-m avg.) using MongoDB's aggregation framework?

like image 318
Fredrik Grundberg Avatar asked Dec 07 '25 06:12

Fredrik Grundberg


1 Answers

It's best to run the entire aggregation at a reasonable interval, and recalculate the whole set. If you're calculating a 3 month average, setup a cronjob to run every night and calculate the average.

var minus3Months = new Date();
minus3Months.setMonth(now.getMonth()-3);
db.myCollection.aggreage([
    {"$match": {"createdAt": {"$gte": minus3Months}}},
    ......
])
like image 83
Benjamin Avatar answered Dec 10 '25 00:12

Benjamin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!