【发布时间】:2016-10-17 02:25:28
【问题描述】:
我的收藏包含以下文件。我想使用聚合来计算里面有多少客户,但我遇到了一些问题。我可以获得总行数,但不能获得总(唯一)客户。
[{
_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
}]
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework