mongodb - 使用 MongoDB 查询在字符串中搜索多个单词/子字符串?

标签 mongodb mongoose mongodb-query

我有一个如图所示的模型

[
    {"_id": "1", "Title": "boat test"},
    {"_id": "2", "Title": "mobiles and extras"}
]

Query_String = "boat"//应返回 [{"_id": "1", "Title": "boat test"}]

Query_String = "boat te"//应返回 [{"_id": "1", "Title": "boat test"}]

Query_String = "mobiles"//应返回 [{"_id": "2", "Title": "mobiles and extras"}]

Query_String = "mob"//应返回 [{"_id": "2", "Title": "mobiles and extras"}]

Query_String = "boat mobile"//应返回 [{"_id": "1", "Title": "boat test"}, {"_id": "2", "Title": "手机和其他内容"}]

我的查询是获取“Title”字段包含给定 Query_String 中的任何单词的所有产品

我尝试过这个,但这仅适用于第一种情况,其中 Query_String 是“boat”

const { Products } = require("../models/Products");

Products.find({
      Title: {
        $regex: `.*${Query_String}.*`,
        $options: "i",
      },
    })

最佳答案

有两种方法,

使用 javascript 正则表达式:

  • 按空格分割字符串并创建数组,映射将字符串转换为正则表达式
  • 尝试 $in Expressions , 要在 $in 查询表达式中包含正则表达式,您只能使用 JavaScript 正则表达式对象(即/pattern/)。例如:
let QString = Query_String.split(" ").map(s => new RegExp(s));
Products.find({
  $or: [
    { Title: { $in: QString } },
    // more fields if needed
    { Category: { $in: QString } }
  ]  
});

使用 $or 条件和 $regex

  • 按空格分割字符串并创建数组,映射以准备单独条件的数组
  • 检查$或条件
let QStringTitle = Query_String.split(" ").map(s => { 
  return {
    {
      Title: {
        $regex: s,
        $options: "i"
      }
    }
  };
});
let QStringCategory = Query_String.split(" ").map(s => { 
  return {
    {
      Category: {
        $regex: s,
        $options: "i"
      }
    }
  };
});
Products.find({ $or: QStringTitle.concat(QStringCategory) });

关于mongodb - 使用 MongoDB 查询在字符串中搜索多个单词/子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66420999/

相关文章:

node.js - 返回重复结果的 Mongoose 查询

mongodb - MongoDB 上的时区查询

javascript - API 是否永久存储从网站提取的数据?

MongoDB:可以将不同的数据库放在不同的驱动器上吗?

javascript - ref 在 mongoose 中是什么意思?

node.js - 从数组中的数组中提取

javascript - 热重载期间识别的模型,仅在服务器重新启动后失败

javascript - 如何执行使用 AND 和 OR 的条件 Mongoose 查询?

mysql - 适合大表的良好数据库,具有简单的键访问

mongodb - 使用 $in 排序不返回所有文档