AggregateCommand.arrayElemAt(value: Expression[]): Object

支持端:小程序 2.7.4 起, 云函数 0.8.1

聚合操作符。返回在指定数组下标的元素。

参数

value: Expression[]

[<array>, <index>]

返回值

Object

API 说明

语法如下:

  1. db.command.aggregate.arrayElemAt([<array>, <index>])

<array> 可以是任意解析为数字的表达式。

<index> 可以是任意解析为整形的表达式。如果是正数,arrayElemAt 返回在 index 位置的元素,如果是负数,arrayElemAt 返回从数组尾部算起的 index 位置的元素。

示例代码

假设集合 exams 有如下记录:

  1. { "_id": 1, "scores": [80, 60, 65, 90] }
  2. { "_id": 2, "scores": [78] }
  3. { "_id": 3, "scores": [95, 88, 92] }

求各个第一次考试的分数和和最后一次的分数:

  1. const $ = db.command.aggregate
  2. db.collection('exams').aggregate()
  3. .project({
  4. first: $.arraElemAt(['$scores', 0]),
  5. last: $.arraElemAt(['$scores', -1]),
  6. })
  7. .end()

返回结果如下:

  1. { "_id": 1, "first": 80, "last": 90 }
  2. { "_id": 2, "first": 78, "last": 78 }
  3. { "_id": 3, "first": 95, "last": 92 }