Fredrik Grundberg
Fredrik Grundberg

Reputation: 31

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?

Upvotes: 3

Views: 832

Answers (1)

Benjamin
Benjamin

Reputation: 749

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}}},
    ......
])

Upvotes: 1

Related Questions