$arrayElemAt (聚合)
定义
兼容性
您可以使用 $arrayElemAt
在以下环境中部署
MongoDB Atlas:云中MongoDB部署的全托管服务
MongoDB Enterprise:基于订阅的自托管MongoDB版本
MongoDB Community:源代码可用、免费使用且可自托管的MongoDB版本
语法
$arrayElemAt
语法如下
{ $arrayElemAt: [ <array>, <idx> ] }
<array>
表达式可以是任何有效的表达式,其结果为数组。
<idx>
表达式可以是任何有效的表达式,其结果为整数。
有关表达式的更多信息,请参阅表达式操作符。
行为
如果
<idx>
表达式解析为零或正整数,$arrayElemAt
返回数组从开头开始的idx
位置的元素。如果
<idx>
表达式解析为负整数,$arrayElemAt
返回数组从结尾开始的idx
位置的元素。如果
idx
超出数组界限,$arrayElemAt
不会返回结果。如果
<array>
表达式解析为一个未定义的数组,$arrayElemAt
返回null
。
示例 | 结果 |
---|---|
{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] } | 1 |
{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] } | 2 |
{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] } | |
{ $arrayElemAt: [ "$undefinedField", 0 ] } | null |
示例
名为 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" }