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

Viewed 35

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.

1 Answers

You should add scheduler/cronJob on server and set time (like 6AM, 12PM etc) and pass them function name that will trigger. If you're using mongodb atlas then check following link. https://www.mongodb.com/docs/atlas/app-services/triggers/scheduled-triggers/

After that you can add this following code in your function to calculate average humidity and temperature.

db.collection.aggregate([
  {
    $limit: 5
  },
  {
    $match: {
      "acquisition-time": {
        $lte: ISODate("2022-05-13T19:33:30.000Z") //Here you can pass date from scheduler or get current data and time from server and covert into ISODate format.
      }
    }
  },
  {
    $group: {
      _id: null,
      avgTemperature: {
        $avg: "$temperature"
      },
      avgHumidity: {
        $avg: "$humidity"
      }
    }
  },
  {
    $project: {
      avgTemperature: 1,
      avgHumidity: 1,  
    }
  }
]);
Related