在一个查询中聚合多个组结果

时间:2015-04-19 10:08:05

标签: mongodb mongodb-query

我想用mongodb中的一些数据填充HTML表格。我有两列填充。如何进行查询,即聚合创建两列,即$ $ sum $ $ count,但$ count应按标志过滤:0。

制作一个检索所有数据的查询是否是正确的方法?有可能吗?

  > db.test.find()
    { "_id" : ObjectId("55a"), "name" : "luk", "col1" : 1, "col2" : 4, "flag": 0}
    { "_id" : ObjectId("55b"), "name" : "luk", "col1" : 2, "col2" : 3, "flag": 0}
    { "_id" : ObjectId("55c"), "name" : "luk", "col1" : 2, "col2" : 5, "flag": 0}
    { "_id" : ObjectId("55d"), "name" : "luk", "col1" : 3, "col2" : 2, "flag": 1}
    { "_id" : ObjectId("56d"), "name" : "luk", "col1" : 3, "col2" : 2, "flag": 1}

    { "_id" : ObjectId("e5e"), "name" : "tom", "col1" : 2, "col2" : 1, "flag": 0}
    { "_id" : ObjectId("55f"), "name" : "tom", "col1" : 2, "col2" : 1, "flag": 0}
    { "_id" : ObjectId("660"), "name" : "tom", "col1" : 4, "col2" : 2, "flag": 1}
    { "_id" : ObjectId("561"), "name" : "tom", "col1" : 4, "col2" : 2, "flag": 1}

我想要结果:

{ name:"luk", sumcol1:"11", count_col2:"3"},
{ name:"tom", sumcol1:"12", count_col2:"2"}

请注意,对于第一次分组 - sumcol1我们会收集所有文档,但对于count_col2,我们会使用标记进行过滤(仅计算带有标记的文字:0) < / p>

在SQL中看起来像这样:

SELECT
  name,
  sum(col1) as suma_col1,
  count(case when flag=0 then col2 end) as count_col2
FROM
  table
group by name

select tab1.name, tab1.suma_col1, tab2.count_col2 FROM
(
SELECT
  name,
  sum(col1) as suma_col1
FROM
  table
group by name
) as tab1
,
(
SELECT
  name,
  count(col2) as count_col2
FROM
  table
  where flag=0
group by name
  ) as tab2
where tab2.name = tab1.name

1 个答案:

答案 0 :(得分:0)

这可以通过aggregation pipeline使用$cond来实现。

db.test.aggregate([
        {
            '$group': 
            {
                '_id': '$name',
                'sumcol1': {'$sum': '$col1'},
                'count_col2': 
                {
                    '$sum' : 
                    { 
                        $cond : 
                        [ 
                            {$eq: [ "$flag", 0 ] },
                            1,
                            0
                        ]
                    }
                }
            }
        }
])

结果: -

{
    "result" : [ 
        {
            "_id" : "tom",
            "sumcol1" : 12,
            "count_col2" : 2
        }, 
        {
            "_id" : "luk",
            "sumcol1" : 11,
            "count_col2" : 3
        }
    ],
    "ok" : 1
}