Definição
Compatibilidade
Você pode utilizar o $arrayElemAt para implantações hospedadas nos seguintes ambientes:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: a versão autogerenciada e baseada em assinatura do MongoDB
MongoDB Community: uma versão com código disponível, de uso gratuito e autogerenciada do MongoDB
Sintaxe
$arrayElemAt tem a seguinte sintaxe:
{ $arrayElemAt: [ <array expression>, <idx> ] }
O <array expression> pode ser qualquer expressão válida que resolva para uma array.
A expressão <idx> pode ser qualquer expressão válida que resolva para um número inteiro.
Para mais informações sobre expressões, consulte Expressões.
Comportamento
If the
<idx>expression resolves to zero or a positive integer,$arrayElemAtreturns the element at theidxposition, counting from the start of the array.If the
<idx>expression resolves to a negative integer,$arrayElemAtreturns the element at theidxposition, counting from the end of the array.If
idxexceeds the array bounds,$arrayElemAtdoes not return a result.If the
<array expression>resolves to an undefined array,$arrayElemAtreturnsnull.
Exemplo | Resultados |
|---|---|
|
|
|
|
| |
|
|
Exemplo
Uma coleção chamada users contém os seguintes documentos:
db.users.insertMany( [ { _id: 1, name: "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }, { _id: 2, name: "li", favorites: [ "apples", "pudding", "pie" ] }, { _id: 3, name: "ahn", favorites: [ "pears", "pecans", "chocolate", "cherries" ] }, { _id: 4, name: "ty", favorites: [ "ice cream" ] } ] )
O exemplo a seguir retorna o primeiro e o último elemento na array favorites:
db.users.aggregate([ { $project: { name: 1, first: { $arrayElemAt: [ "$favorites", 0 ] }, last: { $arrayElemAt: [ "$favorites", -1 ] } } } ])
A operação retorna os seguintes resultados:
[ { _id: 1, name: "dave123", first: "chocolate", last: "apples" }, { _id: 2, name: "li", first: "apples", last: "pie" }, { _id: 3, name: "ahn", first: "pears", last: "cherries" }, { _id: 4, name: "ty", first: "ice cream", last: "ice cream" } ]