$elemMatch(投影)

适用对象: MongoDB vCore

$elemMatch 投影运算符用于投影数组中与指定查询条件匹配的第一个元素。 如果只想从文档中的数组而不是整个数组中检索匹配的元素,则此运算符非常有用。

语法

使用 $elemMatch 投影运算符的语法如下:

db.collection.find({},
    {
      "field": { "$elemMatch": { <query> } }
    }
)

参数

说明
field 包含要从中投影匹配元素的数组的字段。
query 数组中的元素需要匹配的条件。

示例

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

{
  "_id": "34f462fe-5085-4a77-a3de-53f4117466bd",
  "name": "Wide World Importers",
  "location": {
    "lat": -63.5435,
    "lon": 77.7226
  },
  "staff": {
    "totalStaff": {
      "fullTime": 16,
      "partTime": 16
    }
  },
  "sales": {
    "totalSales": 41481,
    "salesByCategory": [
      {
        "categoryName": "Holiday Tableware",
        "totalSales": 41481
      }
    ]
  },
  "promotionEvents": [
    {
      "eventName": "Crazy Deal Days",
      "promotionalDates": {
        "startDate": {
          "Year": 2023,
          "Month": 11,
          "Day": 13
        },
        "endDate": {
          "Year": 2023,
          "Month": 11,
          "Day": 22
        }
      },
      "discounts": [
        {
          "categoryName": "Gift Boxes",
          "discountPercentage": 9
        },
        {
          "categoryName": "Holiday Tableware",
          "discountPercentage": 24
        }
      ]
    },
    {
      "eventName": "Incredible Savings Showcase",
      "promotionalDates": {
        "startDate": {
          "Year": 2024,
          "Month": 5,
          "Day": 11
        },
        "endDate": {
          "Year": 2024,
          "Month": 5,
          "Day": 20
        }
      },
      "discounts": [
        {
          "categoryName": "Ribbons",
          "discountPercentage": 15
        },
        {
          "categoryName": "Gift Bags",
          "discountPercentage": 25
        }
      ]
    }
  ],
  "tag": [
    "#ShopLocal",
    "#FashionStore",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

示例 1:投影数组中的第一个元素,匹配 $elemMatch 条件

此示例从特定文档的 stores 集合中检索 _idname 和第一个匹配的 promotionEvents 数组元素。

db.stores.find(
  {"_id": '34f462fe-5085-4a77-a3de-53f4117466bd'},
  { "_id":1,"name":1,"promotionEvents": { $elemMatch: { "eventName": "Incredible Savings Showcase" } } }
);

查询返回了请求的 _id 文档,其中仅包含来自 promotionEvents 数组的"Incredible Savings Showcase"事件特定详细信息。

{
  "_id": "34f462fe-5085-4a77-a3de-53f4117466bd",
  "name": "Wide World Importers",
  "promotionEvents": [
    {
      "eventName": 'Incredible Savings Showcase',
      "promotionalDates": {
        "startDate": {
          "Year": 2024,
          "Month": 5,
          "Day": 11
        },
        "endDate": {
          "Year": 2024,
          "Month": 5,
          "Day": 20
        }
      },
      "discounts": [
        {
          "categoryName": "Ribbons",
          "discountPercentage": 15
        },
        {
          "categoryName": "Gift Bags",
          "discountPercentage": 25
        }
      ]
    }
  ]
}

限制

  • $elemMatch 不支持文本查询表达式。