【问题标题】:Using find with multiple options for attribute将 find 与多个属性选项一起使用
【发布时间】:2017-06-29 21:55:42
【问题描述】:

我在 React 中有一个 Web 应用程序,我在后端创建了一个使用简单 REST API 的搜索功能,我将一个对象传递给 Mongo 的 find 函数来搜索我的数据库并返回结果.

对象当前的格式如下:

{
    attribute1: { $regex: <searchTerm1>, $options: 'i' };
    attribute2: { $regex: <searchTerm2>, $options: 'i' };
    attribute3: { $regex: <searchTerm3>, $options: 'i' };
}

这将返回我的数据库中的所有文档,其中 attribute1 包含 searchTerm1,attribute2 包含 searchTerm2 等。到目前为止,这部分工作正常,我可以搜索我的属性。

我现在想做的是让用户能够选择多个选项并通过它们进行搜索。例如,用户可以为attribute1 输入searchTerm1 和searchTerm2,为attribute2 输入searchTerm3,它会返回每个包含searchTerm1 searchTerm2 in attribute1 and searchTerm3 的文档。我还没有找到一种方法来做到这一点。

我目前正在做的是为我的前端中的每个属性创建一个包含搜索词的数组,但我不确定如何执行后端部分,我实际上将所有这些词输入到猫鼬中并进行搜索。

【问题讨论】:

    标签: node.js mongodb mongoose full-text-search


    【解决方案1】:

    基于--

    它将返回每个包含 searchTerm1 或 属性 1 中的 searchTerm2 和属性 2 中的 searchTerm3

    相关的解决方案是使用 $and 和 $or like -

    {$and: [{searchTerm3}, {$or: [searchTerm1, searchTerm2]}]}
    

    【讨论】:

    • 如何指定属性?在我给出的那个例子中,我希望 searchTerm3 专门用于属性 2,而 searchTerm1/searchTerm2 专门用于属性 1。
    • 这已经很晚了,但我想通了。您显然不能将 $or 运算符与字符串一起使用,但只需在我的正则表达式字符串中直接使用 or 即可解决它。例如,请参阅我的答案。
    【解决方案2】:

    我想通了。

    我只需要或我在字符串中的搜索词:

    attribute1: { $regex: "<searchTerm1>|<searchTerm2>|<searchTerm3>", $options: 'i' };
    

    这将在数据库中查找具有包含 searchTerm1、searchTerm2 或 searchTerm3 的属性 1 的条目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      相关资源
      最近更新 更多