聚合导致mongoDB计算

时间:2016-09-04 20:06:03

标签: mongodb aggregation-framework

我在MongoDb数据库下工作,我有这个集合:

我有什么?

{
Name : "David",
Type : "First",
Score : 1.66 
}

{
Name : "David",
Type : "Second",
Score : 0.66 
}

{
Name : "Naim",
Type : "First",
Score : 0.33 
}

{
Name : "Naim",
Type : "Second",
Score : 0.10 
}

{
Name : "Joe",
Type : "First",
Score : 1.10 
}
{
Name : "Joe",
Type : "Second",
Score : 2 
}

我想要什么?

我想以这种方式汇总结果:

{
Name : "David",
Type : "First",
Score : 1.66 / ( 0.33 + 1.10 ) // first scores for other documents
}

{
Name : "David",
Type : "Second",
Score : 0.66 / ( 0.10 + 2 ) // second scores for other documents
}

其他名字也一样......

请问我如何实现上述目标?

1 个答案:

答案 0 :(得分:1)

因为这看起来像sql world(我们有CTE表达式)的简单解决方案,然后使用mongo我们可以利用$lookup阶段来模拟CTE。

首先我们计算每个测试组的总和,然后在源上 join 结果,并在$project阶段使用一些算术运算,我们计算结果。

db.dp.aggregate([{
            $group : {
                _id : "$Type",
                "SumScore" : {
                    $sum : "$Score"
                }
            }
        }, {
            $lookup : {

                from : "dp",
                localField : "_id",
                foreignField : "Type",
                as : "lookUp"
            }
        }, {
            $unwind : "$lookUp"
        }, {
            $project : {
                _id : 0,
                "Name" : "$lookUp.Name",
                "Type" : "$_id",
                "Score" : {
                    $divide : ["$lookUp.Score", {
                            $subtract : ["$SumScore", "$lookUp.Score"]
                        }
                    ]
                }
            }
        }
    ])

和输出:

{
    "Name" : "David",
    "Type" : "First",
    "Score" : 1.16083916083916
}

{
    "Name" : "Naim",
    "Type" : "First",
    "Score" : 0.119565217391304
}

{
    "Name" : "Joe",
    "Type" : "First",
    "Score" : 0.552763819095477
}

{
    "Name" : "David",
    "Type" : "Second",
    "Score" : 0.314285714285714
}

{
    "Name" : "Naim",
    "Type" : "Second",
    "Score" : 0.037593984962406
}

{
    "Name" : "Joe",
    "Type" : "Second",
    "Score" : 2.63157894736842
}