当在 mongodb 中的字段中找到任何数组元素时,查询所有文档

Query for all documents when any of the array element is found in a field in mongodb

我有这样一个文档:

[
  {
    "id": 1,
    "active": true,
    "key": []
  },
  {
    "id": 2,
    "active": true,
    "key": [
      {
        "code": "fake_code",
        "ids": [
          ""
        ],
        "labels": [
          "d"
        ]
      }
    ]
  },
  {
    "id": 3,
    "active": true,
    "key": [
      {
        "code": "fake_code",
        "ids": [
          ""
        ],
        "labels": [
          "a",
          "b",
          "c"
        ]
      }
    ]
  }
]

我只想获取文档的 id,其中包含给定数组的任何值(比方说 ["a"、"b"、"c"、"d"])出现在文档的 labels 字段中。

这意味着,由于给定的数组 = ["a", "b", "c", "d"],如果您要查看文档,那么您可以找到具有 id = 2labels 字段中包含 ["d"],而包含 id = 3 的文档在 labels 中包含 ["a", "b", "c"]。

所以,预期的输出就像,

[
  {
    "id": 2
  },
  {
    "id": 3
  }
]

目前,我一直在使用

db.collection.find({
  "key": {
    "$all": [
      {
        "$elemMatch": {
          "ids": {
            "$in": [
              ""
            ]
          },
          "code": "fake_code",
          "labels": {
            "$in": [
              [
                "a",
                "b",
                "c"
              ]
            ]
          }
        }
      }
    ]
  }
},
{
  _id: 0,
  id: 1
})

这个查询能够 return 我只有一个文档有 id = 3,因为在这种情况下我使用给定的数组 = ["a", "b", "c"] .但是是否有可能根据给定的数组(如 [“a”、“b”、“c”、“d”])获取所有文档,这意味着如果任何文档至少具有给定数组的一个匹配值那么查询应该 return 那些文档的 id?

谢谢

您可以使用 $in。如果你在 $elemMatch 里面没有任何条件,你可以直接访问 "key.labels":{$in:[....]}

db.collection.find({
  key: {
    $elemMatch: {
      labels: {
        $in: [
          "a",
          "b",
          "c",
          "d"
        ]
      }
    }
  }
},
{
  _id: 0,
  id: 1
})

工作Mongo playground