MongoDB多字段正则查询返回空数组问题求助
MongoDB多字段模糊查询实现方案
你当前的问题是错误使用了find()方法的参数结构,导致多字段查询返回空数组。find()的第一个参数是查询条件,第二个参数是投影(指定返回哪些字段),你把多个字段的查询条件拆成了多个参数,这不符合语法规范。
错误代码示例
const search = req.query.search || ""; const Rest = await Restaurant.find( {name:{$regex:search,$options:"i"}}, {locality:{$regex:search,$options:'i'}}, {"cuisine.name":{$regex:search,$options:'i'}} )
单个字段查询正常代码
const search = req.query.search || ""; const Rest = await Restaurant.find({name:{$regex:search,$options:"i"}})
正确的多字段或查询实现
要实现任意一个字段匹配搜索词就返回结果,需要用MongoDB的$or操作符把多个字段的查询条件包裹起来,作为find()的第一个参数:
const search = req.query.search || ""; const Rest = await Restaurant.find({ $or: [ { name: { $regex: search, $options: "i" } }, { locality: { $regex: search, $options: "i" } }, { "cuisine.name": { $regex: search, $options: "i" } } ] })
说明
$or操作符会匹配满足数组中任意一个条件的文档$options:"i"表示正则匹配忽略大小写,确保搜索的包容性- 所有查询条件都放在
find()的第一个参数对象里,第二个参数如果不需要指定返回字段可以省略
内容的提问来源于stack exchange,提问作者komala devi
相关产品推荐
相关产品推荐

