MongoDB聚合运算符:$arrayElemAt

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" }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值