MongoDB汇总字段而无需事先知道所有字段 [英] MongoDB aggregate fields without knowing all the fields before hand
本文介绍了MongoDB汇总字段而无需事先知道所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不事先掌握所有指标的情况下计算以下指标的总和?我可以使用聚合框架或MapReduce完成此操作吗?
How can I compute the aggregate of the following metrics without knowing all the metrics before hand? Can I accomplish this using the aggregate framework or 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
}
}
]
我无法执行以下操作,因为这将要求我了解每个指标:
I cannot do something like the following since it would require me to know every metrics:
db.stats.aggregate([
{$group: {
_id: {player: "$player_id"},
points_per_game: { $sum: "$metrics.points_per_game"}
...
])
推荐答案
您可以尝试以下聚合.
将对象转换成键值对数组,然后是$ unwind + $ group以按每个键分组并累加计数.最后一步回到命名键值对象.
Convert the object into array of key value pairs followed by $unwind+$group to group by each key and accumulate the count. Final step to go back to named key value object.
db.colname.aggregate([
{"$addFields":{"metrics":{"$objectToArray":"$metrics"}}},
{"$unwind":"$metrics"},
{"$group":{
"_id":{"id":"$player_id","key":"$metrics.k"},
"count":{"$sum":"$metrics.v"}
}},
{"$group":{
"_id":"$_id.id",
"metrics":{"$mergeObjects":{"$arrayToObject":[[["$_id.key","$count"]]]}}
}}
])
这篇关于MongoDB汇总字段而无需事先知道所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文