MongoDBでは、$arrayElemAt 集計パイプライン演算子は、指定された配列インデックスの要素を返します。
2つの引数を受け入れます。
- アレイ
- 取得する要素のインデックス
例
postsというコレクションがあるとします。 次のドキュメントで:
{
"_id" : 1,
"title" : "Hello World!",
"body" : "This is a test post for the purposes of testing",
"tags" : [
"html",
"css",
"sql",
"xml"
],
"status" : null
}
このドキュメントでは、tags フィールドに配列が含まれています。
$arrayElemAtを使用できます 特定のインデックスの配列要素を返す演算子。
例:
db.posts.aggregate([
{
$project: {
"tag": { $arrayElemAt: [ "$tags", 0 ] }
}
}
]) 結果:
{ "_id" : 1, "tag" : "html" }
この場合、最初の配列要素を返します。配列はゼロベースであるため、0 配列の最初の要素を指します。
ヒント:MongoDB 4.4から、$firstを使用することもできます 配列の最初の要素を返す演算子。
2番目の要素を取得する例を次に示します。
db.posts.aggregate([
{
$project: {
"tag": { $arrayElemAt: [ "$tags", 1 ] }
}
}
]) 結果:
{ "_id" : 1, "tag" : "css" } インデックスの負の値
2番目の引数には負の値を指定できます。これを行うときは、$arrayElemAt 配列の最後から逆方向にカウントします。
例:
db.posts.aggregate([
{
$project: {
"tag": { $arrayElemAt: [ "$tags", -1 ] }
}
}
]) 結果:
{ "_id" : 1, "tag" : "xml" } この場合、配列の最後の要素を取得します。
MongoDB 4.4から、$lastも使用できます 最後の配列要素を取得する演算子。
他のオペレーターとの組み合わせ
$arrayElemAtを使用できます 他のオペレーターと協力して、必要な結果を生み出します。
これを$binarySizeと組み合わせる例を次に示します。 特定の配列要素のサイズを返す演算子。
db.posts.aggregate([
{
$project: {
"tagsSize": { $binarySize: { $arrayElemAt: [ "$tags", 0 ] } }
}
}
]) 結果:
{ "_id" : 1, "tagsSize" : 4 }