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

MongoDB group聚合多条件匹配统计生产部署数量问题咨询

问题解答

你的查询整体逻辑正确,仅存在一处字段引用错误需要修正:

  • 第二个匹配条件中deployments.steps.stages是字符串数组,并非对象数组,你额外添加了.name后缀,会导致该条件无法正确命中符合要求的文档。

修正后的完整查询语句如下:

db.collection.aggregate([
  {
    $match: {
      "createdAt": {
        $gte: ISODate("2020-11-01"),
        $lte: ISODate("2021-11-17")
      },
      $or: [
        {
          "deployments.steps.environments.name": {
            "$in": [
              "Prd",
              "Prod",
              "Production"
            ]
          }
        },
        {
          "deployments.steps.stages": {
            "$in": [
              "Prd",
              "Prod",
              "Production"
            ]
          }
        }
      ]
    }
  },
  {
    $group: {
      _id: "$productId",
      TotalCount: {
        $sum: 1
      },
      SucceededCount: {
        $sum: {
          "$cond": {
            "if": {
              $eq: [
                "$deploymentStatus",
                "Succeeded"
              ]
            },
            "then": 1,
            "else": 0
          }
        }
      },
      FailedCount: {
        $sum: {
          "$cond": {
            "if": {
              $eq: [
                "$deploymentStatus",
                "Failed"
              ]
            },
            "then": 1,
            "else": 0
          }
        }
      },
      CancelledCount: {
        $sum: {
          "$cond": {
            "if": {
              $eq: [
              "$deploymentStatus",
              "Cancelled"
            ]
            },
            "then": 1,
            "else": 0
          }
        }
      },
      NotStartedCount: {
        $sum: {
          "$cond": {
            "if": {
              $eq: [
                "$deploymentStatus",
                "NotStarted"
              ]
            },
            "then": 1,
            "else": 0
          }
        }
      }
    }
  }
])

补充说明:

  • 修正后查询的匹配逻辑完全符合你的要求,可正确筛选出时间范围内的所有生产环境部署记录,分组统计部分按productId维度统计总部署量、各状态部署量的逻辑没有问题。
  • 你原来对createdAt的两个范围判断不需要额外套$and,MongoDB会默认对同字段的多个条件默认执行与操作,简化后的写法更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:45:04