Definition定义
$arrayElemAtReturns 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,$arrayElemAtreturns the element at theidxposition, counting from the start of the array.<idx>表达式解析为零或正整数,$arrayElemAt将返回idx位置的元素,从数组开始计数。If the如果<idx>expression resolves to a negative integer,$arrayElemAtreturns the element at theidxposition, counting from the end of the array.<idx>表达式解析为负整数,$arrayElemAt将返回idx位置的元素,从数组末尾开始计数。If如果idxexceeds the array bounds,$arrayElemAtdoes not return a result.idx超出数组边界,$arrayElemAt不会返回结果。If the如果<array>expression resolves to an undefined array,$arrayElemAtreturnsnull.<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的集合包含以下文档:
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" }
]