通过mongodb选择计数组

时间:2014-07-14 14:54:01

标签: sql mongodb

我试图将以下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"}
    }}
])

1 个答案:

答案 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}
    }}
])