如何在不事先掌握所有指标的情况下计算以下指标的总和?我可以使用聚合框架或MapReduce完成此操作吗?
[
{
player_id: '123',
timestamp: <sometime>,
metrics: {
points_per_game: 1,
rebounds_per_game: 2,
assist_per_game: 3,
}
},
{
player_id: '123',
timestamp: <sometime>,
metrics: {
points_per_game: 1,
rebounds_per_game: 2,
}
},
{
player_id: '345',
timestamp: <sometime>,
metrics: {
points_per_game: 1,
rebounds_per_game: 2,
point_in_the_paint_per_game: 2
}
}
]
我希望得到以下结果
[
{
player_id: '123',
metrics: {
points_per_game: 2,
rebounds_per_game: 4,
assist_per_game: 3,
}
},
{
player_id: '345',
metrics: {
points_per_game: 1,
rebounds_per_game: 2,
point_in_the_paint_per_game: 2
}
}
]
我无法执行以下操作,因为这将要求我了解每个指标:
db.stats.aggregate([
{$group: {
_id: {player: "$player_id"},
points_per_game: { $sum: "$metrics.points_per_game"}
...
])
答案 0 :(得分:2)
您可以尝试以下汇总。
将对象转换为键值对的数组,然后将$ unwind + $ group转换为按每个键分组并累加计数。最后一步回到命名键值对象。
wrap