$arrayElemAt運算子是用來傳回位於指定數位件索引處的專案。 當您需要從檔內的陣列擷取特定元素時,此運算符會很有説明。
語法
{
$arrayElemAt: ["<array>", <idx>]
}
參數
| 參數 | Description |
|---|---|
<array> |
從中擷取項目的陣列參考。 |
<idx> |
要傳回的項目索引。 此索引是以零為起始。 從陣列結尾算起的負索引計數。 |
範例
請參考商店集合中的此範例檔。
{
"_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] }
}
}
])
此查詢會傳回下列結果。
[
{
"_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
}
]
}
}
]