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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:50:25