Tobi
Tobi

Reputation: 2828

count documents in mongodb grouped by a specific field

Example data:

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

Expected output:

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

Additionally it would be nice if I could optional give a from to date to make those kind of statistics by day or month.

Thanks!

Upvotes: 1

Views: 122

Answers (1)

BanksySan
BanksySan

Reputation: 28558

Here you go:

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

Returns:

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

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

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

Upvotes: 1

Related Questions