这是 JSON 的示例。我想通过唯一的“email_address”来计算客户总数,并通过等于“S”的“transactions_status”进行过滤。
预期输出:
{
_id: null,
count: total amount of customers with an unique email address and filtered by status equal S
}
您可以尝试这个聚合管道:
db.collection.aggregate([
{
$match: {
"transaction_info.transaction_status": "S"
}
},
{
$group: {
_id: null,
emails: {
$addToSet: "$payer_info.email_address"
}
}
},
{
$project: {
count: {
$size: "$emails"
}
}
}
]);
就我而言,我也试图计算客户数量,所以我必须使用订单集合来执行此操作,因为订单集合具有客户字段,我可以使用该字段来获取总客户,这是我的聚合
[
{
$match: {
$expr: {
$eq: [
"$shop",
{
$toObjectId:
"653a5a695c5ace2932dd3765",
},
],
},
},
},
{
$match: {
$and: [
{
orderStatus: {
$ne: "deleted",
},
},
],
},
},
{
$group: {
_id: null,
uniqueCustomers: {
$addToSet: "$customer",
},
},
},
{
$project: {
_id: "customers count",
customers: {
$size: "$uniqueCustomers",
},
},
},
]