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

如何在MongoDB中统计列表嵌套数组内isCompleted为true的任务总数

实现查询的聚合语句如下

你示例数据里的isCompleted是字符串类型,所以匹配时需要用字符串值"true",如果你的实际生产数据是布尔类型,替换为true即可:

db.你的集合名.aggregate([
  // 第一步:筛选仅listname为Work的文档,减少后续计算量
  {
    $match: {
      listname: "Work"
    }
  },
  // 第二步:展开listitems数组,把每个子项拆分为单独的文档
  {
    $unwind: "$listitems"
  },
  // 第三步:筛选已完成的任务项
  {
    $match: {
      "listitems.isCompleted": "true"
    }
  },
  // 第四步:统计符合条件的数量,输出字段命名为completedTask
  {
    $count: "completedTask"
  }
])

输出结果

执行后会直接返回你需要的格式:

{ "completedTask" : 2 }

优化写法(无需展开数组,性能更高)

如果不想用$unwind,也可以用$reduce直接在数组层面统计,数据量大的时候效率更好:

db.你的集合名.aggregate([
  {
    $match: { listname: "Work" }
  },
  {
    $project: {
      _id: 0,
      completedTask: {
        $reduce: {
          input: "$listitems",
          initialValue: 0,
          in: {
            $add: [
              "$$value",
              { $cond: [{ $eq: ["$$this.isCompleted", "true"] }, 1, 0] }
            ]
          }
        }
      }
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:21:01