我正在实施mongodb搜索。 搜索对字段值进行查找:
[{
value: "my.string.here"
}, {
value: "my other here"
}{
...
}]
当我输入“ my”时,两个条目都被找到。我的查询看起来像什么,而忽略了第一个条目上的点?那么当我输入“我的字符串”时,第一个元素被返回了吗?
实际上,只有当我输入“ my.string”时,它才有效。
let limit = Number(req.query.limit || 100);
let skip = Number(req.query.skip || 0);
collection.find({
$or: [{
value: new RegExp(req.body.search, "gi")
}, {
tags: {
$in: req.body.search.split(",").map((val) => {
return new RegExp(val, "gi")
})
}
}]
}).skip(skip).limit(limit).toArray((err, result) => {
if (err) {
res.status(500).json(err);
} else {
res.status(200).json(result);
}
});
编辑:
解决方案如下:
let query = {
$or: [{
name: new RegExp(req.body.search, "gi")
}, {
tags: {
$in: req.body.search.split(",").map((val) => {
return new RegExp(val, "gi")
})
}
}, {
name: new RegExp(req.body.search.split(' ').join('.'), "gi")
}, {
name: new RegExp(req.body.search.split(' ').join('_'), "gi")
}, {
name: new RegExp(req.body.search.split(' ').join('-'), "gi")
}]
};
但是我觉得它丑陋而不优雅。有更好的方法吗?