seo织梦网站建设步骤,ppt成品免费下载,做网站怎么偷源码做网站,网站设计功能MongoDB聚合运算符$arrayElemAt用于返回数组中指定位置的元素。
语法
{ $arrayElemAt: [ array, idx ] }array可以是任何能被解析为数组的表达式。idx可以是任何可以被解析为整数的表达式。
使用
如果idx为0或正整数#xff0c;则…MongoDB聚合运算符$arrayElemAt用于返回数组中指定位置的元素。
语法
{ $arrayElemAt: [ array, idx ] }array可以是任何能被解析为数组的表达式。idx可以是任何可以被解析为整数的表达式。
使用
如果idx为0或正整数则返回数组中idx位置的元素数组元素的位置从0开始计算。如果idx为负数则返回数组中从最末尾元素开始第idx元素的值。如果idx超出数组边界则不返回任何结果。如果array解析后不是数组则返回null。
如
举例结果{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] }1{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] }2{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] }{ $arrayElemAt: [ $undefinedField, 0 ] }null
举例
user集合中有下面的文档
{ _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 }