【发布时间】:2017-01-12 04:05:38
【问题描述】:
我有以下数据库值
{
"_id" : ObjectId("5875d82f8447f454b37a947b"),
"updatedAt" : ISODate("2017-01-11T07:01:03.570+0000"),
"createdAt" : ISODate("2017-01-11T07:01:03.570+0000"),
"__v" : NumberInt(0),
"activity_type" : "email_campaign_delivery",
"customer_id" : ObjectId("581ad6f4d1fb4a0e14af159c"),
"email_campaign_id" : ObjectId("5875d82f8447f454b37a9476"),
"email" : "jpnew@tblr.com",
"delivered" : true
}
{
"_id" : ObjectId("5875d82f8447f454b37a947c"),
"updatedAt" : ISODate("2017-01-11T07:01:03.570+0000"),
"createdAt" : ISODate("2017-01-11T07:01:03.570+0000"),
"__v" : NumberInt(0),
"activity_type" : "email_campaign_delivery",
"customer_id" : ObjectId("581ad6f4d1fb4a0e14af159c"),
"email_campaign_id" : ObjectId("5875d82f8447f454b37a9476"),
"email" : "tyt@dffd.com",
"delivered" : false
}
{
"_id" : ObjectId("5875d82f8447f454b37a947d"),
"updatedAt" : ISODate("2017-01-11T07:01:03.570+0000"),
"createdAt" : ISODate("2017-01-11T07:01:03.570+0000"),
"__v" : NumberInt(0),
"activity_type" : "email_campaign_click",
"customer_id" : ObjectId("581ad6f4d1fb4a0e14af159c"),
"email_campaign_id" : ObjectId("5875d82f8447f454b37a9475"),
"email" : "tyt@dffd.com",
"clicked" : true
}
我需要 mongo 聚合查询来获得总交付和不交付结果以及总电子邮件活动计数 我的 mongo 聚合查询是
CampaignActivity.aggregate([{
"$group": {
"_id": null,
"delivered": {
$sum: {
"$cond": {
if: {
$eq: ["$delivered", true]
},
then: 1,
else: 0
}
}
},
"not_delivered": {
$sum: {
"$cond": {
if: {
$eq: ["$delivered", false]
},
then: 1,
else: 0
}
}
},
"total_recipient": {
$sum: {
"$cond": {
if: {
$eq: ["$activity_type", "email_campaign_delivery"]
},
then: 1,
else: 0
}
}
}
}
}, {
"$project": {
"_id": 0,
"not_delivered":1,
"total_recipient":1,
"delivered": 1
}
}],function (err, result) {
if (err) {
console.log(err)
} else {
console.log(result)
}
});
得到以下结果
{
"delivered": 2,
"not_delivered": 7,
"total_recipient": 9
}
如何获得“email_campaign_id”计数而不重复?通过使用上面的例子,它必须是 2。
预期输出:
{ "delivered": 2, "not_delivered": 7, "total_recipient": 9, "total_campaign":2 }
【问题讨论】:
-
请给我们一个你想要的样本输出。
-
尝试 CampaignActivity.distinct("email_campaign_id")。这将返回一个具有所有不同“email_campaign_id”的数组。计数是数组的大小
-
@LakmalVithanage 预期输出:{ "delivered": 2, "not_delivered": 7, "total_recipient": 9, "total_campaign":2 }
-
@felix : 使用聚合查询的任何选项?
标签: mongodb mongoose mongodb-query aggregation-framework