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

MongoDB反向通配符查询失败求助:匹配带*的文档

解决方案

你的查询逻辑方向搞反了:原查询是用目标字符串的完整正则去匹配文档中的数组元素,但实际需要用文档中带*通配符的规则,去判断目标字符串是否符合该规则。

可行查询语句

db.getCollection("Collection").find({
  $expr: {
    $anyElementTrue: {
      $map: {
        input: "$combinations",
        as: "comb",
        in: {
          $regexMatch: {
            input: "IPHONE 13 PRO MAX SR BLU 256GB-AFE",
            regex: { $replaceAll: { input: "$$comb", find: "*", replacement: ".*" } }
          }
        }
      }
    }
  }
})

逻辑说明

  • $replaceAll 将文档中combinations元素里的通配符*替换为正则的.*(匹配任意长度的任意字符)
  • $regexMatch 用转换后的正则去校验目标查询字符串是否符合规则
  • $map 遍历数组中所有元素,$anyElementTrue 判断是否存在至少一个元素匹配成功,满足条件则返回该文档

动态传入查询字符串的写法

如果需要在代码中动态传入查询字符串,可以用变量实现:

const targetStr = "IPHONE 13 PRO MAX SR BLU 256GB-AFE";
db.getCollection("Collection").find({
  $expr: {
    $anyElementTrue: {
      $map: {
        input: "$combinations",
        as: "comb",
        in: {
          $regexMatch: {
            input: targetStr,
            regex: { $replaceAll: { input: "$$comb", find: "*", replacement: ".*" } }
          }
        }
      }
    }
  }
})

原查询失败原因

原查询使用/^IPHONE 13 PRO MAX SR BLUE 256GB-AFE$/正则,要求数组元素必须和目标字符串完全一致,但文档中的元素是IPHONE 13 PRO MAX * 256GB-*,结构和目标字符串不符,且匹配方向错误,因此无法命中结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:12:59