定義
互換性
次の環境でホストされる配置には $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,$arrayElemAtreturns the element at theidxposition, counting from the start of the array.If the
<idx>expression resolves to a negative integer,$arrayElemAtreturns the element at theidxposition, counting from the end of the array.If
idxexceeds the array bounds,$arrayElemAtdoes not return a result.If the
<array expression>resolves to an undefined array,$arrayElemAtreturnsnull.
例 | 結果 |
|---|---|
|
|
|
|
| |
|
|
例
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" } ]