Docs Menu
Docs Home
/
MongoDB マニュアル
/ / /

$arrayElemAt(集計)

項目一覧

  • 定義
  • 互換性
  • 構文
  • 動作
  • その他の参照
$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" }

戻る

$anyElementTrue