gpt4 book ai didi

MongoDB 在事先不知道所有字段的情况下聚合字段

转载 作者:IT老高 更新时间:2023-10-28 12:31:13 29 4
gpt4 key购买 nike

如何在事先不知道所有指标的情况下计算以下指标的汇总?我可以使用聚合框架或 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"}
...
])

最佳答案

您可以尝试以下聚合。

将对象转换为键值对数组,后跟 $unwind+$group 以按每个键分组并累积计数。返回命名键值对象的最后一步。

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 在事先不知道所有字段的情况下聚合字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56640054/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com