我试图将以下sql查询转换为mongodb但我无法完成它
select campaign_id,campaign_name,count(subscriber_id)
group by campaign_id,campaign_name from campaigns;
这是我的部分mongodb查询
db.campaigns.aggregate([
{$group: {
_id: {campaign_id: "$campaign_id",campaign_name: "$campaign_name"},
count: {$sum: "$subscriber_id"}
}}
])
答案 0 :(得分:2)
要模拟SQL count(subscriber_id)
,您可以在管道前添加$match
阶段,以过滤掉subscriber_id
丢失或设置为null
的文档,然后您就可以使用简单的{$sum: 1}
计算:
db.campaigns.aggregate([
{$match: {subscriber_id: {$ne: null}}},
{$group: {
_id: {campaign_id: "$campaign_id",campaign_name: "$campaign_name"},
count: {$sum: 1}
}}
])