MongoDB双$ group聚合

时间:2013-06-17 11:07:41

标签: mongodb

我有几个看起来像这样的文件:

{
        "_id" : ObjectId("50b59cd75bed76f46522c34e"),
        "player_id" : 0,
        "league_id" : 2,
        "results" : [
                {   "discipline" : "football",
                    "score" : 25.15
                },
                {
                        "discipline" : "basketball",
                        "score" : 21.24
                },
                {
                        "discipline" : "cycling",
                        "score" : 68.19
                },]
}

我尝试聚合这些数据。首先展开结果数组,然后只留下“足球”和“循环”,接下来计算平均值结果。这部分我做了,它正在发挥作用。 我的代码:

db.grades.aggregate(
    {$unwind:"$results"},
    {$match: {$or: [{"results.discipline":"football"},{"results.discipline":"cycling"} ]}},
    {$group:{_id:{player_id:"$player_id",league_id:"$league_id"}, 'average':{$avg:"$results.score"}}},
    )

然后我尝试通过 league_id 进行汇总,这意味着,普通玩家会在特定联盟中产生结果,添加到上面的代码: {$group:{_id:"$_id.league_id",aver_league:{$avg:$average}}}

现在代码如下:

db.grades.aggregate(
        {$unwind:"$results"},
        {$match: {$or: [{"results.discipline":"football"},{"results.discipline":"cycling"} ]}},
        {$group:{_id:{player_id:"$player_id",league_id:"$league_id"}, 'average':{$avg:"$results.score"}}},
{$group:{_id:"$_id.league_id",aver_league:{$avg:$average}}}
        )

控制台显示:JavaScript execution failed: ReferenceError: $average is not defined.有什么问题?我在哪里弄错了?是否可以按_id.league_id汇总?

1 个答案:

答案 0 :(得分:4)

试试这个管道:

[
 {$unwind:"$results"}, 
 {$match: {"results.discipline":{$in:["football", "basketball"]}}}, 
 {$group{_id:{player_id:"$player_id",league_id:"$league_id"}, 'average':{$avg:"$results.score"}}} 
]

它适合我的文档:

{
"result" : [
    {
        "_id" : {
            "player_id" : 0,
            "league_id" : 2
        },
        "average" : 23.195
    }
],
"ok" : 1
}

UPD。如果您想再次分组,请 league_id

[{$unwind:"$results"}, 
{$match: {"results.discipline":{$in:["football", "basketball"]}}}, 
{$group:{_id:{player_id:"$player_id",league_id:"$league_id"}, 'average':{$avg:"$results.score"}  }}, 
{$group:{_id:"$_id.league_id", 'average':{$avg:"$average"}  }} ]

{ "result" : [ { "_id" : 2, "average" : 23.195 } ], "ok" : 1 }