Database Manual / Reference / Query Language / Expressions

$arrayElemAt (expression operator)(表达式运算符)

Definition定义

$arrayElemAt
Returns the element at the specified array index.返回指定数组索引处的元素。

Compatibility兼容性

You can use $arrayElemAt for deployments hosted in the following environments:您可以将$arrayElemAt用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

$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 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不会返回结果。
  • If the <array> expression resolves to an undefined array, $arrayElemAt returns null.如果<array>表达式解析为未定义的数组,$arrayElemAt将返回null
Example示例Results结果
{ $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的集合包含以下文档:

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

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另请参阅