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

MongoDB中获取文档指定词汇全部位置 解决$indexOfCP首匹配及大小写敏感问题

解决方案

核心思路

MongoDB原生的$indexOfCP确实存在两个限制:仅返回首个匹配项的索引、默认大小写敏感,可通过4.2版本新增的$regexFindAll运算符一次性解决两个需求:

  1. 正则的i修饰符可实现大小写不敏感匹配
  2. 该运算符会返回所有匹配结果的元数据,提取其中的idx字段即可拿到全部匹配索引

具体实现代码

以你提供的inventory集合匹配item字段中所有foo的需求为例,聚合语句如下:

db.inventory.aggregate(
   [
     {
       $project:
          {
            allCpLocations: {
              $map: {
                input: {
                  $regexFindAll: {
                    input: "$item",
                    regex: "foo",
                    options: "i"
                  }
                },
                as: "matchResult",
                in: "$$matchResult.idx"
              }
            },
          }
      }
   ]
)

效果验证

你给出的测试用例{ $indexOfCP: [ "cafeteria", "e" ] }原生仅返回3,使用上述方案测试:

db.test.aggregate([
  { $documents: [ { testStr: "cafeteria" } ] },
  {
    $project: {
      allMatchIndex: {
        $map: {
          input: { $regexFindAll: { input: "$testStr", regex: "e", options: "i" } },
          as: "res",
          in: "$$res.idx"
        }
      }
    }
  }
])

返回结果为[3,5],覆盖了字符串中所有e的索引位置。

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

如果你的MongoDB版本不支持$regexFindAll,可先将字符串拆分为单字符数组,遍历数组统一转大小写后匹配,记录对应下标即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:15:05