对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$arrayElemAt(表达式操作符)

$arrayElemAt

返回位于指定数组索引处的元素。

可以使用 $arrayElemAt 查找托管在以下环境中的部署:

  • MongoDB Atlas:用于云中 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 的集合包含以下文档:

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

以下示例将返回 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" }
]