Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose query for documents from last 24 hours, only one document per hour

I am coding an app in which there are some weather sensors that send air's temperature and humidity to the server every 5 minutes.

I would like to draw a chart of how the temperature and humidity change i.e overnight. My idea is to draw the chart basing on data from last 24 hours.

I cannot figure it out by myself, so I thought maybe I could seek help here. Of course, each measurement document has a field called createdAt which has the timestamp of the moment it has been created.

I need to build a mongoose query that will retrieve measurements collected in the last 24 hours, but only take one measurement from each hour. With the 5min time interval with the device's measurements I will have 12 documents created every hour. I would like to retrieve only one of them per each hour.

So far I was able to come up with this (used gt to get the last 24 hours measurements, dont know how to get only one document per each hour):

Measurements.find({ "createdAt": { $gt: new Date(Date.now() - 24*60*60 * 1000) } })

like image 333
Aleksander Sadaj Avatar asked Oct 11 '25 08:10

Aleksander Sadaj


1 Answers

You can use below aggregation to get first and last document from each hour.

$sort to order documents by createdAt followed by $group on hour to output first and last document for each hour.

$$ROOT is system variable to access the whole document.

Measurements.aggregate([
  {"$match" : {"createdAt":{"$gt":new Date(Date.now() - 24*60*60 * 1000)}}},
  {"$sort":{"createdAt":-1}},
  {"$group":{
    "_id":{"$hour":"$createdAt"},
    "first":{"$first":"$$ROOT"},
    "last":{"$last":"$$ROOT"}
  }}
])
like image 192
s7vr Avatar answered Oct 16 '25 12:10

s7vr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!