You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合操作中如何统计布尔字段的True值数量

解决MongoDB统计布尔字段True值数量的问题

针对你只需要统计accept_one和reject_one字段为true的数量需求,你可以对原聚合查询做两种调整,下面是具体实现:

方法一:先过滤再统计(逻辑直观)

在$facet的每个子管道中,先通过$match筛选出目标字段为true的文档,再进行分组统计:

db.yourCollection.aggregate([
  {
    $facet: {
      "accept_one": [
        { $match: { accept_one: true } },
        { $group: { _id: true, c: { $sum: 1 } } }
      ],
      "reject_one": [
        { $match: { reject_one: true } },
        { $group: { _id: true, c: { $sum: 1 } } }
      ]
    }
  }
])

这个思路很直接:先把不需要的false文档过滤掉,剩下的都是符合条件的,再统计总数即可,结果会直接返回你想要的单个true计数条目。

方法二:用条件求和(性能更优)

如果想减少聚合阶段的数量,可以用$cond条件表达式在一次$group中完成两个字段的统计,最后再格式化结果:

db.yourCollection.aggregate([
  {
    $group: {
      _id: null,
      accept_one_true_count: { $sum: { $cond: [{ $eq: ['$accept_one', true] }, 1, 0] } },
      reject_one_true_count: { $sum: { $cond: [{ $eq: ['$reject_one', true] }, 1, 0] } }
    }
  },
  {
    $project: {
      _id: 0,
      accept_one: { _id: true, c: '$accept_one_true_count' },
      reject_one: { _id: true, c: '$reject_one_true_count' }
    }
  }
])

这里$cond会判断每个文档的目标字段是否为true,是则累加1,否则累加0。最后通过$project把统计结果转换成你期望的结构。

结果验证

基于你提供的示例数据,两种方法都会返回如下结果:

[
  {
    "accept_one": { "_id": true, "c": 3 },
    "reject_one": { "_id": true, "c": 3 }
  }
]

内容的提问来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 22:07:40