【问题标题】:Combine multiple search options into one in MongoDB and node.js在 MongoDB 和 node.js 中将多个搜索选项合二为一
【发布时间】:2020-07-13 21:12:33
【问题描述】:

拥有这个工作代码:

const aggregateOptions = [];

// search by name
if (req.query.name) {
  aggregateOptions.push({ $match: { name: { $regex: req.query.name, $options: 'i' } } });
}

// search by surname
if (req.query.surname) {
  aggregateOptions.push({ $match: { surname: req.query.surname } });
}

// search by nationality
if (req.query.nationality) {
  aggregateOptions.push({ $match: { nationality: req.query.nationality } });
}

它负责构建用于搜索的查询。问题是它们是分开工作的,我希望能够将一个字符串写入搜索栏,并编写代码来搜索所有 3 个字段。

例如,现在有一个名称搜索栏,当我写“my_string”时,它只检查是否有一个 name="my_string" 并且我想检查所有这些。

类似 name="my_string" OR surname="my_string" OR nationality="my_string"。

所以我用 $or 写了这个:

  aggregateOptions.push({
      $or: [
        { nationality: req.query.nationality },
        { surname: req.query.surname },
        { name: { $regex: req.query.name, $options: 'i' } },
      ],
    });

这似乎是错误的并返回此错误消息:“$or is not allowed in this atlas tier”

【问题讨论】:

    标签: javascript node.js mongodb mongoose filter


    【解决方案1】:

    您可以为此使用文本搜索。在 mongo 中,您可以创建一个包含国籍、姓氏和姓名的文本索引,例如

    db.collection.createIndex( { nationality: "text", surname: "text", name: "text" } )
    

    现在您可以使用类似的方式查询您的收藏集

    db.collection.find({$text: { $search:req.query.name } })
    

    这将对所有 3 个字段执行文本搜索并返回任何匹配项。

    这里有一些资源:

    https://docs.mongodb.com/manual/core/index-text/ https://docs.mongodb.com/manual/reference/operator/query/text/ 希望这会有所帮助!

    【讨论】:

    • 我试过了,它说db is not defined。应该如何定义?
    • 第一个命令(createIndex)应该在数据库中完成。它将创建一个可搜索的索引,然后 find() 必须在您的代码中完成,具体取决于您使用的驱动程序。 docs.mongodb.com/drivers 查看我发布的链接或查看指南以了解如何设置。
    猜你喜欢
    • 2013-12-02
    • 1970-01-01
    • 2014-07-31
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-05
    • 2013-08-20
    相关资源
    最近更新 更多