$arrayElemAt (aggregation)
On this page本页内容
Definition定义
$arrayElemAt
-
Returns the element at the specified array index.返回指定数组索引处的元素。$arrayElemAt
has the following syntax:具有以下语法:{ $arrayElemAt: [ <array>, <idx> ] }
The<array>
expression can be any valid expression that resolves to an array.<array>
表达式可以是解析为数组的任何有效表达式。The<idx>
expression can be any valid expression that resolves to an integer.<idx>
表达式可以是解析为整数的任何有效表达式。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
Behavior行为
If the如果<idx>
expression resolves to zero or a positive integer,$arrayElemAt
returns the element at theidx
position, counting from the start of the array.<idx>
表达式解析为零或正整数,$arrayElemAt
将返回idx
位置的元素,从数组开始计数。If the如果<idx>
expression resolves to a negative integer,$arrayElemAt
returns the element at theidx
position, counting from the end of the array.<idx>
表达式解析为负整数,$arrayElemAt
将返回idx
位置的元素,从数组末尾开始计数。If如果idx
exceeds the array bounds,$arrayElemAt
does not return a result.idx
超过数组界限,$arrayElemAt
不会返回结果。If the如果<array>
expression resolves to an undefined array,$arrayElemAt
returnsnull
.<array>
表达式解析为未定义的数组,$arrayElemAt
将返回null
。
{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] } | 1 |
{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] } | 2 |
{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] } | |
{ $arrayElemAt: [ "$undefinedField", 0 ] } | null |
Example实例
A collection named 名为users
contains the following documents:users
的集合包含以下文档:
{ "_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" ] }
The following example returns the first and last element in the 以下示例返回favorites
array:favorites
数组中的第一个和最后一个元素:
db.users.aggregate([
{
$project:
{
name: 1,
first: { $arrayElemAt: [ "$favorites", 0 ] },
last: { $arrayElemAt: [ "$favorites", -1 ] }
}
}
])
The operation returns the following results:该操作返回以下结果:
{ "_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" }