我有一个如图所示的模型
[
{"_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/