$arrayElemAt(数组表达式)

适用对象: MongoDB vCore

$arrayElemAt 运算符用于返回指定数组索引处的元素。 当需要从文档的数组中提取特定元素时,此运算符非常有用。

语法

{ "$arrayElemAt": [ "<array>", "<idx>" ] }

parameters

说明
<array> 从中检索元素的数组参考。
<idx> 要返回的元素的索引。 该索引从零开始。 负索引从数组末尾开始计数。

示例

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

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
  "location": {"lat": 60.1441, "lon": -141.5012},
  "staff": {"totalStaff": {"fullTime": 2, "partTime": 0}},
  "sales": {
    "salesByCategory": [
      {"categoryName": "DJ Cables", "totalSales": 1000},
      {"categoryName": "DJ Headphones", "totalSales": 35921}
    ],
    "fullSales": 3700
  },
  "promotionEvents": [
    {
      "eventName": "Cyber Monday Event",
      "promotionalDates": {
        "startDate": {"Year": 2024, "Month": 8, "Day": 1},
        "endDate": {"Year": 2024, "Month": 8, "Day": 7}
      },
      "discounts": [{"categoryName": "DJ Speakers", "discountPercentage": 25}]
    },
    {
      "eventName": "Black Friday Event",
      "promotionalDates": {
        "startDate": {"Year": 2024, "Month": 8, "Day": 1},
        "endDate": {"Year": 2024, "Month": 8, "Day": 7}
      },
      "discounts": [{"categoryName": "DJ Speakers", "discountPercentage": 25}]
    },
    {
      "eventName": "Mega Discount Days",
      "promotionalDates": {
        "startDate": {"Year": 2024, "Month": 5, "Day": 11},
        "endDate": {"Year": 2024, "Month": 5, "Day": 18}
      },
      "discounts": [{"categoryName": "DJ Lights", "discountPercentage": 20}]
    }
  ],
  "tag": [
    "#ShopLocal", "#NewArrival", "#FashionStore", "#SeasonalSale", "#FreeShipping", "#MembershipDeals"
  ]
}

示例 1:返回数组字段中的第一个元素

该示例从搜索存储的 promotionEvents 数组中检索第一个事件详细信息。

db.stores.aggregate([
  { $match: { name: "Lakeshore Retail | DJ Equipment Stop - Port Cecile" } },
  {
    $project: {
      firstPromotionEvent: { $arrayElemAt: ["$promotionEvents", 0] } 
    }
  }
])

该查询返回查询存储的第一个升级事件 json。

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "firstPromotionEvent": {
    "eventName": "Cyber Monday Event",
    "promotionalDates": {
      "startDate": { "Year": 2024, "Month": 8, "Day": 1 },
      "endDate": { "Year": 2024, "Month": 8, "Day": 7 }
    },
    "discounts": [
      { "categoryName": "DJ Speakers", "discountPercentage": 25 }
    ]
  }
}