Mongodb Aggregate Moving Average calculation

I need to calculate the moving average of the element in monogodb document using aggregation query. For example consider the following documents in a collection.

{"Timecode": 1482242192, "Data": 143} //12pm 
{"Timecode": 1482238584, "Data": 140} //11pm
{"Timecode": 1482234984, "Data": 137} //10pm
{"Timecode": 1482231384, "Data": 135} //9pm
{"Timecode": 1482227784, "Data": 142} //8pm
{"Timecode": 1482224184, "Data": 146} //7pm
{"Timecode": 1482220584, "Data": 150} //6pm
.
.
//Continues as follows

Each data is obtained every hour as shown in comments. I want to calculate moving avaerage on Data every 5 hours.

So for the above data, I want to calculate an average of data between (12pm to 8pm), (11pm to 7pm), (10pm to 6pm) and so on

Therefore for the above data I need to get 3 document as results.

[Note: I want to do it using mongodb aggregate function only. I don’t want to do it on the frontend JavaScript]

Thanks in advance.

1 Like