Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
L'operatore $arrayElemAt viene usato per restituire l'elemento in corrispondenza dell'indice di matrice specificato. Questo operatore è utile quando è necessario estrarre un elemento specifico da una matrice all'interno dei documenti.
Sintassi
{
$arrayElemAt: ["<array>", <idx>]
}
Parametri
| Parametro | Description |
|---|---|
<array> |
Riferimento di matrice da cui viene recuperato l'elemento. |
<idx> |
Indice dell'elemento da restituire. L’indice è in base zero. Un indice negativo viene conteggiato dalla fine della matrice. |
Esempi
Si consideri questo documento di esempio dalla raccolta negozi.
{
"_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"
]
}
Esempio 1: Restituire il primo elemento da un campo di matrice
Questa query recupera i primi dettagli dell'evento dalla promotionEvents matrice per l'archivio cercato.
db.stores.aggregate([
{ $match: { name: "Lakeshore Retail | DJ Equipment Stop - Port Cecile" } },
{
$project: {
firstPromotionEvent: { $arrayElemAt: ["$promotionEvents", 0] }
}
}
])
Questa query restituisce il risultato seguente.
[
{
"_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
}
]
}
}
]