MongoDB Count 匹配查询的文档的真假值总数 [英] MongoDB Count total number of true and false values for documents matching a query

查看:16
本文介绍了MongoDB Count 匹配查询的文档的真假值总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下数据,我将如何使用 MongoDB 对聚合查询的支持来计算 pollId 为hr4946-113"的记录集合的赞成票和反对票总数.

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 }

这将是预期的结果.

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

推荐答案

聚合框架是你的答案:

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

基本上是 $group 运算符通过键"和分组运算符"收集所有数据,例如 $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.

给你:

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

你可以很傻,使用 $cond 运算符有条件地评估字段值:

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

结果:

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

这篇关于MongoDB Count 匹配查询的文档的真假值总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆