对于数据库中的每个实体,我都有带有价格的时间戳数组,我想按时间戳对它们进行分组,并获得该时间戳的平均价格。
我目前正在使用mongoose,我尝试了各种分组依据函数,但我没有找到按每个元素分组的解决方案。
{
_id : "52b632a9e4f2ba13c82ccd23",
history-dates : [2019-10-1, 2019-10-2, 2019-10-3, 2019-10-4]
history-prices : [1000.0, 2000.0, 500.0, 1500.0]
},
{
_id : "52b632a9e4f2ba13c82ccd23",
history-dates : [2019-10-1, 2019-10-2, 2019-10-3, 2019-10-4]
history-prices : [2000.0, 3000.0, 1500.0, 2500.0]
}我想要的结果如下:
date: 2019-10-1
avgPrice : 1500.0我如何才能做到这一点,并提前感谢。
发布于 2019-11-11 14:06:01
正如Neil所指出的,你应该稍微改变一下文档结构
因此引入一个array类型字段historicalPrices,其结构为:[{ date: "2019-10-1", price: 1000.0 }]
然后,您可以应用以下查询来获得按日期分组的平均价格
db.mycollection.aggregate([
{ $unwind: "historicalPrices" },
{ $group: {
"_id": "$historicalPrices.date",
avgPrice:{ $avg: "$historicalPrices.price" }
}
}
])
//Result: [{ _id: "2019-10-01", avgPrice: 1500.0 }, ....]了解有关Aggregation Pipeline、$unwind、$group、$avg的更多信息
https://stackoverflow.com/questions/58691268
复制相似问题