如何按时间戳分组值

时间:2019-11-04 10:14:21

标签: arrays mongodb group-by mongodb-query aggregation-framework

对于数据库中的每个实体,我都有一组带有价格的时间戳记,我希望将它们按时间戳记分组,并获取该时间戳记的平均价格。

我目前正在使用猫鼬,并且尝试了各种分组功能,但是我没有找到按每个元素分组的解决方案。

{ 
 _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

我要如何实现这一目标,并提前致谢。

1 个答案:

答案 0 :(得分:1)

正如Neil指出的那样,您应该对文档结构进行一些更改

因此引入historicalPrices类型的字段array,其结构为:[{ 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