本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$arrayElemAt
Amazon DocumentDB 中的$arrayElemAt運算子可讓您依索引位置從陣列擷取 元素。當您需要存取文件中陣列欄位中的特定元素時,此功能特別有用。
參數
-
array:要從中擷取 元素的輸入陣列。 -
index:要擷取之 元素的以零為基礎的索引位置。此值必須是非負整數。
範例 (MongoDB Shell)
在此範例中,我們將示範如何使用 $arrayElemAt運算子,從miles集合中的flight_miles陣列擷取特定元素。
建立範例文件
db.miles.insertMany([ { "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ]}, { "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 2560, 890, 2780 ]}, { "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 880 ]} ]);
查詢範例
db.miles.aggregate([ { $project: { "_id": 1, "first_mile": { $arrayElemAt: [ "$flight_miles", 0 ] }, "last_mile": { $arrayElemAt: [ "$flight_miles", -1 ] } }} ]);
輸出
{ "_id" : 1, "first_mile" : 1205, "last_mile" : 880 }
{ "_id" : 2, "first_mile" : 1205, "last_mile" : 2780 }
{ "_id" : 3, "first_mile" : 1205, "last_mile" : 880 }
在此範例中,我們使用 $arrayElemAt運算子來擷取每個文件flight_miles陣列的第一個和最後一個元素。
程式碼範例
若要檢視使用 $arrayElemAt命令的程式碼範例,請選擇您要使用的語言標籤: