MongoDB聚合运算符:$arrayElemAt

MongoDB聚合运算符$arrayElemAt用于返回数组中指定位置的元素。

语法

{ $arrayElemAt: [ <array>, <idx> ] }
  • 可以是任何能被解析为数组的表达式。
  • 可以是任何可以被解析为整数的表达式。

使用

  • 如果为0或正整数,则返回数组中位置的元素,数组元素的位置从0开始计算。
  • 如果为负数,则返回数组中从最末尾元素开始,第元素的值。
  • 如果超出数组边界,则不返回任何结果。
  • 如果解析后不是数组,则返回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" }

你可能感兴趣的:(mongodb,mongodb,数据库)