【问题标题】:Find percent in mongo在 mongo 中查找百分比
【发布时间】:2020-02-29 14:50:06
【问题描述】:

我有一个包含 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
}

【问题讨论】:

标签: mongodb mongodb-query


【解决方案1】:

这个输入:

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

]);

产生这个输出,其中_idClass

{
        "_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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 2019-12-05
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多