MongoDB聚合 - 特定计数特定元素

时间:2016-06-15 19:47:04

标签: mongodb mongodb-query aggregation-framework

我的藏品包含以下文件。我想使用聚合来计算内部有多少客户,但我遇到了一些问题。我可以得到总排,但不是总(独特)客户。

[{
    _id: "n001",
    channel: "Kalipare",
    trans: {
        _id: "trans001",
        customerID: "customerCXLA93",
        customerName: "Kalipare Fried Chicked"
    }
}, {
    _id: "n002",
    channel: "Kalipare",
    trans: {
        _id: "trans002",
        customerID: "customerCXLA93",
        customerName: "Kalipare Fried Chicked"
    }
}, {
    _id: "n003",
    channel: "Kalipare",
    trans: {
        _id: "trans003",
        customerID: "customerPWR293",
        customerName: "Kalipare Papabun"
    }
}, {
    _id: "n004",
    channel: "Kalipare",
    trans: {
        _id: "trans004",
        customerID: "customerPWR293",
        customerName: "Kalipare Papabun"
    }
}, {
    _id: "n005",
    channel: "Tumpakrejo",
    trans: {
        _id: "trans005",
        customerID: "customerPWR293",
        customerName: "Tumpakrejo Big Burger"
    }
}]

这是我的代码。

db.col.aggregate([
    { $group: {
        _id: "$channel",
        totalRow: { $sum: 1 }
    } }
])

我该如何计算独特的客户并生成这样的数据。

[{
    _id: "Kalipare",
    totalRow: 4,
    totalCustomer: 2
}, {
    _id: "Tumpakrejo",
    totalRow: 1,
    totalCustomer: 1
}]

1 个答案:

答案 0 :(得分:1)

要获取唯一客户计数,需要使用 $addToSet 运算符在组管道中创建一组唯一客户ID。获得数组后,使用 $size 管道中的 $project 运算符来获取长度,这将为您提供唯一计数。< / p>

运行以下聚合管道将为您提供所需的结果:

db.col.aggregate([
    {
        "$group": {
            "_id": "$channel",
            "totalRows": { "$sum": 1 },
            "totalCustomer": { "$addToSet": "$trans.customerID" }
        }
    },
    {
        "$project": {
            "totalRows": 1,
            "totalCustomers": { "$size": "$totalCustomer" }
        }
    }
])

<强>输出

{
    "result" : [ 
        {
            "_id" : "Tumpakrejo",
            "totalRows" : 1,
            "totalCustomers" : 1
        }, 
        {
            "_id" : "Kalipare",
            "totalRows" : 4,
            "totalCustomers" : 2
        }
    ],
    "ok" : 1
}