【问题标题】:How to search for multiple ObjectIds using MongoDB Atlas Search如何使用 MongoDB Atlas Search 搜索多个 ObjectId
【发布时间】:2022-01-04 20:27:10
【问题描述】:

我在 MongoDB 集合中有文档,这些文档引用了不同集合中的 ObjectId。例如,我的 Orders 集合包含带有 CustomerId 的文档。

使用 MongoDB Atlas 搜索,我定义了一个索引,允许我使用以下语法搜索 CustomerId 字段:

{
  "index": "Orders",
  "equals": {
    "path": "CustomerId"
    "value": new ObjectId("5m5....")
  }
}

(上面的 sn-p 来自我的聚合管道的 $search 阶段。)

但现在我需要使用多个客户 ID 执行 OR 搜索。不幸的是,在使用 equals 运算符时,我不能只指定一个 ObjectIds 数组。 https://docs.atlas.mongodb.com/atlas-search/equals/

在搜索具有多个 ObjectId 的 MongoDB Atlas Search 索引时,我有哪些选择?

【问题讨论】:

    标签: mongodb mongodb-atlas mongodb-atlas-search


    【解决方案1】:

    您可以使用带有 should 子句和 minimumShouldMatch 设置为 1 - https://docs.atlas.mongodb.com/atlas-search/compound/ 的复合查询。

    【讨论】:

    • 我也有同样的想法!使用 should 子句可以提高包含我的目标 CustomerIds 的文档的分数,但它不会阻止其他文档出现在我的结果中。理想情况下,我想在 must 或 filter 子句中执行此操作。
    • 使用“minimumShouldMatch”设置为 1 有帮助吗? (在同一个帮助页面中提到)
    • 它确实...只要我不需要将不同字段上的过滤器添加到 should 数组中。不过,它符合我当前的用例。
    • 您可以在复合查询中嵌套复合查询。因此,您可以在 must 中包含两个带有 shoulds 的化合物,它们都有自己的 minimumShouldOccur。这将允许您单独过滤。
    • 啊,我不知道复合查询可以这样嵌套。在这种情况下,这绝对是最好的答案。谢谢!
    【解决方案2】:

    一种方法是在$search 阶段之后使用$match 阶段。然后您可以使用$in 运算符搜索多个ObjectId。请注意,这种方法会影响性能,如下所述:

    https://docs.atlas.mongodb.com/atlas-search/performance/#-match-aggregation-stage-usage

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2021-12-26
      • 2021-12-10
      • 2022-09-23
      • 2022-06-13
      • 2021-06-07
      • 2023-03-28
      • 2021-09-15
      • 1970-01-01
      相关资源
      最近更新 更多