AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

$arrayElemAt(式演算子)

$arrayElemAt

指定された配列インデックスの要素を返します。

次の環境でホストされる配置には $arrayElemAt を使用できます。

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
  • MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン

  • MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン

$arrayElemAt の構文は次のとおりです。

{ $arrayElemAt: [ <array expression>, <idx> ] }

<array expression> は、配列に解決される任意の有効な式にすることができます。

<idx> 式は、整数に解決される任意の有効な式にすることができます。

式の詳細については、「式 」を参照してください。

  • 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.

  • If the <idx> expression resolves to a negative integer, $arrayElemAt returns the element at the idx position, counting from the end of the array.

  • If idx exceeds the array bounds, $arrayElemAt does not return a result.

  • If the <array expression> resolves to an undefined array, $arrayElemAt returns 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" }
]