$arrayElemAt (aggregation)

On this page本页内容

Definition定义

$arrayElemAt

New in version 3.2.版本3.2中的新功能。

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>表达式可以是解析为整数的任何有效表达式

  • If the <idx> expression resolves to zero or a positive integer, $arrayElemAt returns the element at the idx 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 the idx 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不会返回结果。

For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Example示例Results结果
{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] } 1
{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] } 2
{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] }  

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" }

See Also参阅