我有一个Node.JS应用程序。它每秒从设备获取温度数据,并将其存储在MongoDB中。现在我需要找到过去24个月的数据,并需要得到过去24小时内每小时的平均温度。我有最近24小时的数据。但是找不到一种方法来获得平均数据/小时。有什么方法可以实现这个解决方案吗?
mongoose.connection.db.collection(templateId)
.aggregate([
{
$match: {
"deviceId":deviceId,
"entryDayTime":{
$lt : new Date(),
$gte: new Date(new Date().setHours(new Date().getHours()-24))
}
}
},
{
$sort: {"entryDayTime":-1}
},
{
$group: {
_id: null,
average: {$avg:"$temperature"},
}
},
{
$project:{
_id:0,average:1
}
}]这是我到目前为止为获取最近24小时数据而编写的聚合代码。
发布于 2019-12-05 23:03:35
假设你在创建时有一个时间戳,这很容易,使用$group。
db.collection.aggregate([
{
$group: {
_id: {$hour: "$timeField"},
avg: {$avg: "$tempature"}
}
}
])https://stackoverflow.com/questions/59197013
复制相似问题