MongoDB Count total number of true and false value

2020-04-15 11:47发布

问题:

Using the following data, how would I count the total number of yes and no votes for a collection of records with pollId "hr4946-113" using MongoDBs support for aggregate queries.

{ "_id" : ObjectId("54abcdbeba070410146d6073"), "userId" : "1234", "pollId" : "hr4946-113", "vote" : true, "__v" : 0 }
{ "_id" : ObjectId("54afe32fec4444481b985711"), "userId" : "12345", "pollId" : "hr2840-113", "vote" : true, "__v" : 0 }
{ "_id" : ObjectId("54b66de68dde7a0c19be987b"), "userId" : "123456", "pollId" : "hr4946-113", "vote" : false }

This would be the expected Result.

{
   "yesCount": 1,
   "noCount":1
}

回答1:

The aggregation framework is your answer:

db.collection.aggregate([
    { "$match": { "pollId": "hr4946-113" } },
    { "$group": {
        "_id": "$vote",
        "count": { "$sum": 1 }
    }}
])

Basically the $group operator gathers all the data by "key", and "grouping operators" like $sum work on the values. In this case, just adding 1 on the boundaries to indicate a count.

Gives you:

{ "_id": true, "count": 1 }, 

You can be silly and expand that into a single document response using the $cond operator to conditionally evaluate the field values:

db.collection.aggregate([
    { "$match": { "pollId": "hr4946-113" } },
    { "$group": {
        "_id": "$vote",
        "count": { "$sum": 1 }
    }},
    { "$group": {
        "_id": null,
        "yesCount": {
            "$sum": {
                "$cond": [ "_id", 1, 0 ]
            }
        },
        "noCount": {
            "$sum": {
                "$cond": [ "_id", 0, 1 ]
            }
        }
    }},
    { "$project": { "_id": 0 } }
])

And the result:

{ "yesCount": 1, "noCount": 0 }