AggregateCommand.last(value: Expression): Object

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

聚合操作符。返回指定字段在一组集合的最后一条记录对应的值。仅当这组集合是按照某种定义排序( sort )后,此操作才有意义。

参数

value: Expression

表达式

返回值

Object

API 说明

last 的语法如下:

  1. db.command.aggregate.last(<表达式>)

表达式是形如 $ + 指定字段 的字符串。

last 只能在 group 阶段被使用,并且需要配合 sort 才有意义。

示例代码

假设集合 students 的记录如下:

  1. { "group": "a", "name": "stu1", "score": 84 }
  2. { "group": "a", "name": "stu2", "score": 96 }
  3. { "group": "b", "name": "stu3", "score": 80 }
  4. { "group": "b", "name": "stu4", "score": 100 }

如果需要得到所有记录中 score 的最大值,可以先将所有记录按照 score 排序,然后取出最后一条记录的 last

  1. const $ = db.command.aggregate
  2. db
  3. .collection('students')
  4. .aggregate()
  5. .sort({
  6. score: 1
  7. })
  8. .group({
  9. _id: null,
  10. max: $.last('$score')
  11. })
  12. .end()

返回的数据结果如下:

  1. { "_id": null, "max": 100 }