首页 > 解决方案 > 在 mongo 中查找百分比

问题描述

我有一个包含 2 个文档的集合,如下所示。

{
_id:1,
Score: 30,
Class:A,
School:X
}
{
Score:40,
Class:A,
School:Y
}

我需要帮助编写查询以找出如下分数的百分比

{
School:X,
Percent:30/70
}
{
School:Y
Percent:40/70
}

标签: mongodbmongodb-query

解决方案


这个输入:

var r =
[
 {"school":"X", "class":"A", "score": 30}
 ,{"school":"Y", "class":"A", "score": 40}
 ,{"school":"Z", "class":"A", "score": 20}
 ,{"school":"Y", "class":"B", "score": 50}
 ,{"school":"Z", "class":"B", "score": 17}
         ];

运行此管道:

db.foo.aggregate([

// Use $group to gather up the class and save the inputs via $push                                           
{$group: {_id: "$class", tot: {$sum: "$score"}, items: {$push: {score:"$score",school:"$school"}}} }

// Now we have total by class, so just "reproject" that array and do some nice                               
// formatting as requested:                                                                                  
,{$project: {
        items: {$map: {  // overwrite input array $items; this is OK                                         
            input: "$items",
            as: "z",
            in: {
                    school: "$$z.school",
                    pct: {$concat: [ {$toString: "$$z.score"}, "/", {$toString:"$tot"} ]}
                }
            }}
    }}

]);

产生此输出,_id其中Class

{
        "_id" : "A",
        "items" : [
                {"school" : "X",   "pct" : "30/90"},
                {"school" : "Y",   "pct" : "40/90"},
                {"school" : "Z",   "pct" : "20/90"}
                ]
}
{
        "_id" : "B",
        {"school" : "Y",   "pct" : "50/67"},
        {"school" : "Z",   "pct" : "17/67"}
        ]
}

$unwind如果您愿意,可以从这里开始。


推荐阅读