mongoDB以2%的$ group汇总

时间:2017-04-20 15:10:31

标签: mongodb mongodb-query aggregation-framework

我的数据集:

{
    "codepostal": 84000,
    "siren": 520010234,
    "type": "home"
},
{
    "codepostal": 84000,
    "siren": 0,
    "type": "home"
},
{
    "codepostal": 84000,
    "siren": 450123003,
    "type": "appt"
} ...

我的管道(总数是一个整数):

var pipeline = [
        {
            $match: { codepostal: 84000 }
        },
        {
            $group: {
                _id: { type: "$type" },
                count: { $sum: 1 }
            }
        },
        {
            $project: {
                percentage: { $multiply: ["$count", 100 / total] }
            }
        },
        {
            $sort: { _id: 1 }
        }
    ];

结果:

[ { _id: { type: 'appt' }, percentage: 66 },
  { _id: { type: 'home' }, percentage: 34 } ]

当“警笛”设置为0或其他数字时,预期结果将计算在内。

Count siren = 0 =>部分
Count siren!= 0 =>亲

[ { _id: { type: 'appt' }, totalPercent: 66, proPercent: 20, partPercent: 80},
  { _id: { type: 'home' }, totalPercent: 34, proPercent: 45, partPercent: 55 } ]

非常感谢你的帮助!!

1 个答案:

答案 0 :(得分:1)

根据siren字段的值,您可以使用$cond为专业/部分文档获取0或1。然后,很容易计算每种类型文档的总数:

[
    {
        $match: { codepostal: 84000 }
    },
    {
        $group: {
            _id: { type: "$type" },
            count: { $sum: 1 },
            countPro: { $sum: {$cond: [{$eq:["$siren",0]}, 0, 1]} },
            countPart: {$sum: {$cond: [{$eq:["$siren",0]}, 1, 0]} }
        }
    },

    {
        $project: {
            totalPercent: { $multiply: ["$count", 100 / total] },
            proPercent: { $multiply: ["$countPro", {$divide: [100, "$count"]}] },
            partPercent: { $multiply: ["$countPart", {$divide: [100, "$count"]}] }
        }
    },

    {
        $sort: { _id: 1 }
    }
]

请注意,我使用$ divide来计算相对于类型组中文档计数的专业/部分百分比。

对于您的样本文档(总计= 3),输出将为:

[
    {
        "_id" : { "type" : "appt" },
        "totalPercent" : 33.3333333333333,
        "proPercent" : 100,
        "partPercent" : 0
    },
    {
        "_id" : { "type" : "home" },
        "totalPercent" : 66.6666666666667,
        "proPercent" : 50,
        "partPercent" : 50
    }
]