猿问

Golang MongoDB (mgo) 聚合与嵌套数组

我有以下形式的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.value.team1的平均时data.statistics.gsm.type ==“攻击”使用MongoDB的Golang司机氧化镁。到目前为止,代码我已经试过(带有一个或两个组声明如下):


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}}


千巷猫影
浏览 261回答 1
1回答

MMMHUHU

我总是发现它有助于获得JSON的一个漂亮的打印预览。这里是你说你从第一组发言得到:[  {  "_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运算符将数组分解为一组文档,然后您应该能够按照您尝试使用的方式将它们分组{$avg: "$value.team1"}。所以用来产生聚合整体管道将是:$match -> $group1 -> $unwind -> $group2。只要记住这条管道的每个阶段对前一阶段,这就是为什么你的所产生的数据进行操作的data.statistics.gsm.value.team1部分是不正确的。
随时随地看视频慕课网APP

相关分类

Go
我要回答