AggregateCommand.reduce(value: any): Object

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

聚合操作符。类似 JavaScript 的 reduce 方法,应用一个表达式于数组各个元素然后归一成一个元素。

参数

value: any

返回值

Object

API 说明

语法如下:

  1. db.command.aggregate.reduce({
  2. input: <array>
  3. initialValue: <expression>,
  4. in: <expression>
  5. })
字段说明
input输入数组,可以是任意解析为数组的表达式
initialValue初始值
in用来作用于每个元素的表达式,在 in 中有两个可用变量,value 是表示累计值的变量,this 是表示当前数组元素的变量

示例代码

简易字符串拼接

假设集合 player 有如下记录:

  1. { "_id": 1, "fullname": [ "Stephen", "Curry" ] }
  2. { "_id": 2, "fullname": [ "Klay", "Thompsom" ] }

获取各个球员的全名,并加 Player: 前缀:

  1. const $ = db.command.aggregate
  2. db.collection('player').aggregate()
  3. .project({
  4. info: $.reduce({
  5. input: '$fullname',
  6. initialValue: 'Player:',
  7. in: $.concat(['$$value', ' ', '$$this']),
  8. })
  9. })
  10. .end()

返回结果如下:

  1. { "_id": 1, "info": "Player: Stephen Curry" }
  2. { "_id": 2, "info": "Player: Klay Thompson" }

获取各个球员的全名,不加前缀:

  1. const $ = db.command.aggregate
  2. db.collection('player').aggregate()
  3. .project({
  4. name: $.reduce({
  5. input: '$fullname',
  6. initialValue: '',
  7. in: $.concat([
  8. '$$value',
  9. $.cond({
  10. if: $.eq(['$$value', '']),
  11. then: '',
  12. else: ' ',
  13. }),
  14. '$$this',
  15. ]),
  16. })
  17. })
  18. .end()

返回结果如下:

  1. { "_id": 1, "name": "Stephen Curry" }
  2. { "_id": 2, "name": "Klay Thompson" }