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

如何使用Mongoose在MongoDB中搜索指定关键词并获取匹配位置索引

解决方案

你已经通过$regex完成了匹配文档的筛选,只需在返回结果中遍历文档,调用JS字符串方法计算关键词起始索引即可,无需额外修改数据库查询逻辑。

完整实现代码

// 定义搜索关键词
const targetKeyword = 'Neque';
// 构造与查询逻辑一致的正则(此处i代表不区分大小写,和你原查询参数保持一致)
const matchRegex = new RegExp(targetKeyword, 'i');

Subtitle.find({ content: { $regex: matchRegex } }, (error, data) => {
  if (error) {
    console.log(error);
    return;
  }
  // 处理每一条匹配的文档
  data.forEach(doc => {
    // 获取关键词第一次出现的起始索引
    const startIndex = doc.content.search(matchRegex);
    // 按你要求的格式输出
    console.log(`name ${doc.name}`);
    console.log(`Index: ${startIndex}`);
  })
});

拓展说明

  • 如果需要获取单篇文档中关键词所有出现位置的索引,可以用matchAll方法实现:
const getAllMatchIndexes = (content, regex) => {
  return [...content.matchAll(regex)].map(item => item.index);
}
  • 如果搜索关键词包含正则特殊字符(如$、.、*等),构造正则前需要先对关键词做转义处理,避免匹配逻辑异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:06:07