mongodb聚合$ avg

时间:2015-03-12 11:37:16

标签: mongodb aggregation-framework

文档如下所示:

   {
    "_id" : ObjectId("361de42f1938e89b179dda42"),
    "user_id" : "u1",
    "evaluator_id" : "e1",
    "candidate_id" : ObjectId("54f65356294160421ead3ca1"),
    "OVERALL_SCORE" : 150,
    "SCORES" : [ 
      { "NAME" : "asd", "OBTAINED_SCORE" : 30}, { "NAME" : "acd", "OBTAINED_SCORE" : 36}
      ]
   }

聚合功能:

 db.coll.aggregate([ {$unwind:"$SCORES"}, {$group : { _id : { user_id : "$user_id", evaluator_id : "$evaluator_id"}, AVG_SCORE : { $avg : "$SCORES.OBTAINED_SCORE" }}} ])

假设有两个文件相同" user_id" (比如说u1)和不同" evaluator_id" (比如说e1)和e2)。

例如:

1)平均值将如此工作((30 + 20)/ 2 = 25)。这对我有用。

2)但是对于{evaluator_id:" e1" {" NAME"}文件,得分为30 :" asd" }和{evaluator_id:" e2" {" NAME"}文件,得分为0 :" asd" }。在这种情况下,我希望 AVG_SCORE 30(不是(30 + 0)/ 2 = 15)

是否可以通过聚合?

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:1)

可以在$unwind$group聚合管道之间放置 $match ,以首先过滤符合指定条件的数组,以包含在平均值中计算,即获得的分数,其中获得的分数不等于0 "SCORES.OBTAINED_SCORE" : { $ne : 0 }

db.coll.aggregate([ 
    {
        $unwind: "$SCORES"
    },     
    { 
        $match : { 
            "SCORES.OBTAINED_SCORE" : { $ne : 0 } 
        } 
    },
    {
        $group : { 
            _id : { 
                user_id : "$user_id", 
                evaluator_id : "$evaluator_id"
            }, 
            AVG_SCORE : { 
                $avg : "$SCORES.OBTAINED_SCORE" 
            }
        }
     } 
 ])

例如,此文档的聚合结果:

{
    "_id" : ObjectId("5500aaeaa7ef65c7460fa3d9"),
    "user_id" : "u1",
    "evaluator_id" : "e1",
    "candidate_id" : ObjectId("54f65356294160421ead3ca1"),
    "OVERALL_SCORE" : 150,
    "SCORES" : [ 
        {
            "NAME" : "asd",
            "OBTAINED_SCORE" : 0
        }, 
        {
            "NAME" : "acd",
            "OBTAINED_SCORE" : 36
        }
    ]
}

将产生:

{
    "result" : [ 
        {
            "_id" : {
                "user_id" : "u1",
                "evaluator_id" : "e1"
            },
            "AVG_SCORE" : 36
        }
    ],
    "ok" : 1
}