本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$arrayElemAt
Amazon DocumentDB 中的$arrayElemAt运算符允许您按索引位置从数组中检索元素。当您需要访问文档中数组字段中的特定元素时,这特别有用。
参数
-
array: 要从中检索元素的输入数组。 -
index:要检索的元素从零开始的索引位置。此值必须是非负整数。
示例(MongoDB 外壳)
在此示例中,我们将演示如何使用$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命令的代码示例,请选择要使用的语言的选项卡: