$elemMatch(数组查询)

适用对象: MongoDB vCore

$elemMatch 运算符用于将包含数组字段的文档与至少一个与所有指定查询条件匹配的元素进行匹配。 需要查找具有指定元素的数组文档时,此运算符特别有用。

语法

$elemMatch 运算符的基本语法如下所示:

db.collection.find({ <field>: { $elemMatch: { <query1>, <query2>, ... } } })

参数

说明
field 文档中包含要查询的数组的字段。
query 数组中至少有一个元素必须满足的条件。

示例

让我们了解 stores 数据集中的示例 json 的用法。

[
  {
    "_id": "91de5201-8194-44bf-848f-674e8df8bf5e",
    "name": "Adatum Corporation",
    "promotionEvents": [
      {
        "discounts": [
          { "categoryName": "DJ Cases", "discountPercentage": 6 },
          { "categoryName": "DJ Mixers", "discountPercentage": 14 }
        ]
      },
      {
        "discounts": [
          { "categoryName": "DJ Headphones", "discountPercentage": 19 },
          { "categoryName": "DJ Speakers", "discountPercentage": 13 }
        ]
      },
      {
        "discounts": [
          { "categoryName": "DJ Lighting", "discountPercentage": 12 },
          { "categoryName": "DJ Accessories", "discountPercentage": 6 }
        ]
      }
    ]
  }
]

示例 1:在数组中查找元素列表中的特定元素

本示例查找 stores 集合中至少有一个折扣的前两个文档,其 promotionEvents 数组中的类别名称为“DJ Lighting”。 查询仅返回这些文档的 _idpromotionEvents.discounts 字段。

db.stores.find(  {"promotionEvents.discounts":{$elemMatch:{"categoryName":"DJ Lighting"}}}
                ,{ _id: 1, "promotionEvents.discounts": 1 }).limit(2)

我们收到了返回的以下文档。

{
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "promotionEvents": [
      {
        "discounts": [
          {
            "categoryName": "DJ Turntables",
            "discountPercentage": 18
          },
          {
            "categoryName": "DJ Mixers",
            "discountPercentage": 15
          }
        ]
      },
      {
        "discounts": [
          {
            "categoryName": "DJ Lighting",
            "discountPercentage": 14
          },
          {
            "categoryName": "DJ Cases",
            "discountPercentage": 20
          }
        ]
      }
    ]
  },
  {
    "_id": "91de5201-8194-44bf-848f-674e8df8bf5e",
    "promotionEvents": [
      {
        "discounts": [
          {
            "categoryName": "DJ Cases",
            "discountPercentage": 6
          },
          {
            "categoryName": "DJ Mixers",
            "discountPercentage": 14
          }
        ]
      },
      {
        "discounts": [
          {
            "categoryName": "DJ Headphones",
            "discountPercentage": 19
          },
          {
            "categoryName": "DJ Speakers",
            "discountPercentage": 13
          }
        ]
      },
      {
        "discounts": [
          {
            "categoryName": "DJ Lighting",
            "discountPercentage": 12
          },
          {
            "categoryName": "DJ Accessories",
            "discountPercentage": 6
          }
        ]
      }
    ]
}