// return the average number of visits going back backMonth months from currentMonth (inclusive both ends)
movingAverage = function(currentMonth, backMonths) {
var result = db.visitsByMonth.aggregate([
{ "$match" : { "month" : { "$lte" : currentMonth, "$gte" : currentMonth - backMonths } } },
{ "$group" : { "_id" : 0, "sum" : { "$sum" : "$visits" }, "count" : { "$sum" : 1 } } },
{ "$project" : { "average" : { "$divide" : ["$sum", "$count"] } } }
])
return result.toArray()[0].average
}> movingAverage(4, 0)
500
> movingAverage(4, 1)
450
> movingAverage(4, 2)
400
> movingAverage(4, 3)
350
> movingAverage(4, 4)
300
-Will