Calculate the average of two fields considering entries of last 5 mins on given datetime

I am using a collection to collect humidity and temperature from a sensor. This sensor is publishing data every minute. here is the data sample.

/* 1 */
{
    "temperature" : 30.80,
    "humidity" : 77.90,
    "acquisition-time" : ISODate("2022-05-13T19:23:29.000Z")
}

/* 2 */
{
    "temperature" : 30.80,
    "humidity" : 77.90,
    "acquisition-time" : ISODate("2022-05-13T19:26:30.000Z")
}

/* 3 */
{
    "temperature" : 30.80,
    "humidity" : 77.80,
    "acquisition-time" : ISODate("2022-05-13T19:29:30.000Z")
}

/* 4 */
{
    "temperature" : 30.75,
    "humidity" : 77.72,
    "acquisition-time" : ISODate("2022-05-13T19:31:30.000Z")
}

/* 5 */
{
    "temperature" : 31.70,
    "humidity" : 77.70,
    "acquisition-time" : ISODate("2022-05-13T19:33:30.000Z")
}

/* 6 */
{
    "temperature" : 30.80,
    "humidity" : 77.80,
    "acquisition-time" : ISODate("2022-05-13T19:34:30.000Z")
}

I want to find the temperature and humidity every day at 6 AM, 12 PM, and 10 PM. To find the temperature and humidity at 6 AM I need to consider the last 5 minutes of data before 6 AM then calculate the average.

My approach would be to

1 - a $match stage to filter documents for the given day
2 - a $set stage to a period field with possible values 6am, 12pm, 10pm using your 5min ranges.
3 - a $group stage with _id:$period using the $avg accumulator

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.