On this page
$arrayElemAt (aggregation)
在本页面
Definition
$arrayElemAt
- 3.2 版中的新功能。
返回指定数组索引处的元素。
$arrayElemAt具有以下语法:
{ $arrayElemAt: [ <array>, <idx> ] }
<array>
表达式可以是任何有效的expression,只要它解析为数组即可。
<idx>
表达式可以是任何有效的expression,只要它可以解析为整数即可。
如果为正,则$arrayElemAt从数组的开头算起,返回
idx
位置的元素。如果为负,则$arrayElemAt从数组末尾开始返回位于
idx
位置的元素。
如果idx
超出数组范围,则$arrayElemAt不返回任何结果。
有关表达式的更多信息,请参见Expressions。
Behavior
有关表达式的更多信息,请参见Expressions。
Example | Results |
---|---|
{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] } |
1 |
{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] } |
2 |
{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] } |
Example
名为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" ] }
下面的示例返回favorites
数组中的第一个和最后一个元素:
db.users.aggregate([
{
$project:
{
name: 1,
first: { $arrayElemAt: [ "$favorites", 0 ] },
last: { $arrayElemAt: [ "$favorites", -1 ] }
}
}
])
该操作返回以下结果:
{ "_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" }