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

MongoDB聚合查询:按子文档字段正则匹配统计步骤类型数量

解决MongoDB正则匹配统计步骤类型的问题

这个问题我之前碰到过,大概率是MongoDB版本的问题——$regexMatch是MongoDB 4.2版本才正式引入的操作符,如果你的集群版本低于这个,就会抛出「Unrecognized expression '$regexMatch'」的错误。下面给你两种可行的解决方案,根据你的版本情况选择:

方案1:使用$regexMatch(MongoDB 4.2+)

如果你的MongoDB版本已经是4.2或更高,只需要把集成步骤的过滤条件写对即可。针对i(***key***)这种格式,我们可以用正则^i\(.+\)$来精准匹配(以i(开头、)结尾的字符串)。

完整的查询语句如下:

{
  "$project": {
    "process.name": 1,
    "basicSteps": {
      "$size": {
        "$filter": {
          "input": "$process.steps",
          "as": "items",
          "cond": { "$eq": [ "$$items.stepType", "basic" ] }
        }
      }
    },
    "inputSteps": {
      "$size": {
        "$filter": {
          "input": "$process.steps",
          "as": "items",
          "cond": { "$eq": [ "$$items.stepType", "input" ] }
        }
      }
    },
    "integrationSteps": {
      "$size": {
        "$filter": {
          "input": "$process.steps",
          "as": "items",
          "cond": {
            "$regexMatch": {
              "input": "$$items.stepType",
              "regex": "^i\\(.+\\)$"
            }
          }
        }
      }
    }
  }
}

注:如果你的key部分不会包含右括号,也可以用^i\([^)]+\)$作为正则,这样匹配更严谨,避免意外匹配到嵌套括号的情况。

方案2:兼容低版本(MongoDB <4.2)

如果暂时无法升级MongoDB版本,可以用老版本支持的$regex操作符来实现相同的效果,直接把正则作为$filter的条件即可:

完整的查询语句如下:

{
  "$project": {
    "process.name": 1,
    "basicSteps": {
      "$size": {
        "$filter": {
          "input": "$process.steps",
          "as": "items",
          "cond": { "$eq": [ "$$items.stepType", "basic" ] }
        }
      }
    },
    "inputSteps": {
      "$size": {
        "$filter": {
          "input": "$process.steps",
          "as": "items",
          "cond": { "$eq": [ "$$items.stepType", "input" ] }
        }
      }
    },
    "integrationSteps": {
      "$size": {
        "$filter": {
          "input": "$process.steps",
          "as": "items",
          "cond": { "$regex": "$$items.stepType", "^i\\(.+\\)$" }
        }
      }
    }
  }
}

两种方案都能帮你统计出符合i(***key***)格式的步骤数量,你可以根据自己的MongoDB版本来选择对应的写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:21:49