问题描述
我正在编写一个应用程序,其中有一些天气传感器每 5 分钟向服务器发送一次空气温度和湿度.
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.
我想绘制温度和湿度如何变化的图表,即一夜之间.我的想法是根据过去 24 小时的数据绘制图表.
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.
我自己无法解决,所以我想也许我可以在这里寻求帮助.当然,每个测量文档都有一个名为 createdAt
的字段,它具有创建时的时间戳.
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.
我需要构建一个 mongoose 查询,该查询将检索过去 24 小时内收集的测量值,但每小时只进行一次测量.在设备测量的 5 分钟时间间隔内,我每小时将创建 12 个文档.我想每小时只检索其中一个.
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.
到目前为止,我能够想出这个(使用 gt
来获取过去 24 小时的测量值,不知道如何每小时只获取一个文档):
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) } })
推荐答案
使用聚合
这是一篇很棒的文章了解如何对文档进行分组,然后为每个文档选择一项.
this is a great article for how to group your documents then pick one item per document.
您还需要过滤过去 24 小时的文档,然后根据时间戳为查找和 hour
进行投影.
You also need to filter docs for last 24 hours, then project for find and hour
from timestamp.
如果您需要(比方说持续 48 小时),则需要按小时和天分组.
您的查询将是这样的
collection.aggregate([
{
"$filter": {
"createdAt": { $gt: new Date(Date.now() - 24*60*60 * 1000) }
}
},
{
"$project": {
"h": {"$hour" : "$createdAt"},
"original_doc": "$$ROOT"
}
},
{
"$group": {
"_id": { "hour": "$h" },
"docs": { $push: "$original_doc" }
}
},
{
$replaceRoot: {
newRoot: { $arrayElemAt: ["$docs", 0] }
}
}
])
这篇关于Mongoose 查询过去 24 小时内的文档,每小时只有一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!