MongoDB 流水线条件计数

MongoDB pipeline conditional counting

集合中的文档包含 titleactive 字段。 active 字段是布尔值。我的目标是按 title 分组并计算所有记录。最后,我想统计 active 为 true 的文档。

此查询进行计数,但总计和活动总是相等。为什么条件不只计算 active 为 true 的文档?

这是我的管道:

[
    { 
        "$group" : { 
            "_id" : { 
                "student᎐campus᎐title" : "$student.campus.title"
            }, 
            "total" : { 
                "$sum" : NumberInt(1)
            }, 
            "active" : { 
                "$sum" : { 
                    "$cond" : [
                        { 
                            "active" : true
                        }, 
                        1.0, 
                        0.0
                    ]
                }
            }
        }
    }
]

您的代码无法运行,因为您正在评估 expression objects instead of operator expressions

试试下面的工作版本:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$title",
      "total": {
        "$sum": 1
      },
      "active": {
        "$sum": {
          "$cond": [
            "$active",
            1.0,
            0.0
          ]
        }
      }
    }
  }
])

这里是Mongo playground供大家参考。


编辑:感谢@wernfriedDomscheit 的建议,这里有一个使用 $toInt for MongoDB v4.0+

的更简洁的版本
db.collection.aggregate([
  {
    "$group": {
      "_id": "$title",
      "total": {
        "$sum": 1
      },
      "active": {
        "$sum": {
          "$toInt": "$active"
        }
      }
    }
  }
])

Mongo playground