gpt4 book ai didi

mongodb - 带有嵌套数组的 Golang MongoDB (mgo) 聚合

转载 作者:IT王子 更新时间:2023-10-29 01:43:01 24 4
gpt4 key购买 nike

我有以下形式的 MongoDB 数据:

{"_id":"53eb9a5673a57578a10074ec","data":{"statistics":{"gsm":[{"type":"Attacks","value":{"team1":66,"team2":67}},{"type":"Corners","value":{"team1":8,"team2":5}},{"type":"Dangerous attacks","value":{"team1":46,"team2":49}},{"type":"Fouls","value":{"team1":9,"team2":14}},{"type":"Free kicks","value":{"team1":18,"team2":10}},{"type":"Goals","value":{"team1":2,"team2":1}},{"type":"Goal kicks","value":{"team1":10,"team2":11}},{"type":"Offsides","value":{"team1":1,"team2":4}},{"type":"Posession","value":{"team1":55,"team2":45}},{"type":"Shots blocked","value":{"team1":4,"team2":1}},{"type":"Shots off target","value":{"team1":7,"team2":5}}]}}}

我想在 data.statistics.gsm.type == "Attacks"时使用 Golang MongoDB 驱动程序 mgo 获取 data.statistics.gsm.value.team1 的平均值。到目前为止我尝试过的代码(使用下面的一个或两个组语句):

pipeline := []bson.M{
bson.M{"$match": bson.M{"kick_off.utc.gsm.date_time": bson.M{"$gt": start, "$lt": end}}},
bson.M{
"$group": bson.M{
"_id": "$gsm_id",
"event_array" : bson.M{"$first": "$data.statistics.gsm"}}},
bson.M{
"$group": bson.M{
"_id": "$type",
"avg_attack" : bson.M{"$avg": "$data.statistics.gsm.value.team1"}}}}

只有第一个组语句,我得到了下面的结果,但是第二个组语句没有帮助我得到平均值。

[{"_id":1953009,"event_array":[{"type":"Attacks","value":{"team1":48,"team2":12}},{"type":"Corners","value":{"team1":12,"team2":0}},{"type":"Dangerous attacks","value":{"team1":46,"team2":7}},{"type":"Fouls","value":{"team1":10,"team2":3}},{"type":"Free kicks","value":{"team1":5,"team2":12}},{"type":"Goals","value":{"team1":8,"team2":0}}

最佳答案

我总是发现获取 json 的 pretty-print View 很有帮助。这是您从第一个小组声明中得到的内容:

[  
{
"_id":1953009,
"event_array":[
{
"type":"Attacks",
"value":{
"team1":48,
"team2":12
}
},
{
"type":"Corners",
"value":{
"team1":12,
"team2":0
}
},
...

现在您使用的第二组语句:

"$group": bson.M{
"_id": "$type",
"avg_attack" : bson.M{"$avg": "$data.statistics.gsm.value.team1"}
}

您尝试对第一组语句的结果取 data.statistics.gsm.value.team1 的平均值,但第一组结果中不存在该平均值声明,所以它当然不会给你一个平均值。

我建议您查看 $unwind operator,而不是您使用的方法将数组分解为一组文档,然后您应该能够按照您在此处尝试使用 {$avg: "$value.team1"} 的方式对它们进行分组。

因此,用于生成聚合的整个管道将是:$match -> $group1 -> $unwind -> $group2。请记住,管道的每个阶段都对前一阶段产生的数据进行操作,这就是为什么您的 data.statistics.gsm.value.team1 部分不正确的原因。

关于mongodb - 带有嵌套数组的 Golang MongoDB (mgo) 聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26914225/

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