【问题标题】:How to find all documents from an array field compared against an array如何从与数组比较的数组字段中查找所有文档
【发布时间】:2021-03-07 06:02:54
【问题描述】:

我有一个 Person 模型,其字段是一个值数组,我的输入是另一个值数组。

我需要找到两个数组之间有匹配值的所有人:

const Person1 = {
  inner: { field: ["1", "2", "3"] }
}

const Person2 = {
  inner: { field: ["2", "3"] }
}

const Person3 = {
  inner: { field: ["1"] }
}

const Person4 = {
  inner: { field: ["3"] }
}

const searchAgainst = ["1", "2"]

所以给定这 4 个具有这些值的人,当使用 searchAgainst 搜索 Person 模型时,它应该返回 Person1, Person2, Person3,因此即使只包含 searchAgainst 的一个值,也应该返回它。

我尝试过这样做:

const foundPeople = await Person.find({ inner: { field: { $in: searchAgainst }}});

const foundPeople = await Person.find({ "inner.field": { $in: searchAgainst }});

但它不起作用,它没有返回任何找到的人。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您应该使用$elemMatch 运算符。 From MongoDB documentation:

    $elemMatch 运算符匹配包含数组字段且至少有一个元素匹配所有指定查询条件的文档。

    所以它似乎满足了你想要的:

    Person.find({
      "inner.field": {
        $elemMatch: {
          $in: [
            "1",
            "2"
          ]
        }
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2018-11-05
      • 1970-01-01
      • 2016-10-06
      • 2013-11-06
      • 2021-04-14
      • 2019-05-21
      • 1970-01-01
      • 2019-03-05
      • 2012-08-12
      相关资源
      最近更新 更多