计算mongodb中按特定字段分组的文档

时间:2016-04-25 20:33:44

标签: mongodb mapreduce

示例数据:

{ "category" : "abc" }
{ "category" : "abc", "ready": true }
{ "category" : "xyz" }
{ "category" : "foo", "ready": true }
{ "category" : "foo", "ready": true }
{ "category" : "foo" }

预期产出:

{
    "abc": {
        "count": 2,
        "ready": 1
    },
    "xyz": {
        "count": 1,
        "ready": 0
    },
    "foo": {
        "count": 3,
        "ready": 2
    }
}

此外,如果我可以选择提供迄今为止的日期或月份来制作这类统计数据,那将是很好的。

谢谢!

1 个答案:

答案 0 :(得分:1)

你走了:

db.foo.aggregate([{
    $group: {
        _id: "$category",
        count: { $sum: 1},
        ready: { 
            $sum: {
                $cond: {
                    if: "$ready",
                    then: 1,
                    else: 0
                }
            }
        }
    }
}])

返回:

/* 1 */
{
    "_id" : "foo",
    "count" : 3,
    "ready" : 2
}

/* 2 */
{
    "_id" : "xyz",
    "count" : 1,
    "ready" : 0
}

/* 3 */
{
    "_id" : "abc",
    "count" : 2,
    "ready" : 1
}