【问题标题】:How to search and find multiple field values... using MongoDB and I tried with regex如何搜索和查找多个字段值...使用 MongoDB,我尝试使用正则表达式
【发布时间】:2022-10-15 18:07:54
【问题描述】:

我试图在使用 .find() 方法搜索时找到 3 个不同的字段值,它提供完整数据或仅提供一个。

这是我给出的代码:

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'})

正如我在 .find() 中提到的多个字段一样,我得到一个空数组作为输出。

如果我使用下面的代码(即)只找到一个字段,我会得到输出。

const Rest = await Restaurant.find({name:{$regex:search,$options:"i"}})

如果我搜索 3 个字段 name/locality/cuisine.name 中的任何一个,我应该得到适当的输出。

【问题讨论】:

    标签: regex mongodb model


    【解决方案1】:

    您的原始查询不正确。这些条件应该是分组成一个参数。它应该如下所示:

    const Rest = await Restaurant.find({
      name: {
        $regex: search,
        $options: "i"
      },
      locality: {
        $regex: search,
        $options: "i"
      },
      "cuisine.name": {
        $regex: search,
        $options: "i"
      }
    })
    

    上面的查询将匹配条件(必须满足所有过滤条件)。

    相反,您需要在或者$or 运算符的条件(需要满足任一过滤条件)。

    解决方案

    const Rest = await Restaurant.find({
      $or: [
        {
          name: {
            $regex: search,
            $options: "i"
          }
        },
        {
          locality: {
            $regex: search,
            $options: "i"
          }
        },
        {
          "cuisine.name": {
            $regex: search,
            $options: "i"
          }
        }
      ]
    })
    

    Demo @ Mongo Playground

    【讨论】:

    • 非常感谢,它有效......即使我尝试使用 $or 但使用 {} 而不是 [] 并收到错误......
    【解决方案2】:

    您可以查看 Mongodb 中的 $and 运算符和 $or 运算符,如果要匹配所有给定参数,则可以使用 $and 运算符,如果必须匹配,则可以使用 $or 运算符。像这样:

    const Rest = await Restaurant.find({
      $and: [
        { name: { $regex: search, $options: "i" } },
        { locality: { $regex: search, $options: "i" } },
        { "cuisine.name": { $regex: search, $options: "i" } },
      ],
    });
    

    请参阅文档:

    $and operator

    $or operator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多