AggregateCommand.switch(value: any): Object

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

聚合操作符。根据给定的 switch-case-default 计算返回值、

参数

value: any

返回值

Object

API 说明

switch 的使用形式如下:

  1. switch({
  2. branches: [
  3. case: <表达式>, then: <表达式>,
  4. case: <表达式>, then: <表达式>,
  5. ...
  6. ],
  7. default: <表达式>
  8. })

示例代码

假设集合 items 的记录如下:

  1. { "_id": "0", "name": "item-a", "amount": 100 }
  2. { "_id": "1", "name": "item-b", "amount": 200 }
  3. { "_id": "2", "name": "item-c", "amount": 300 }

我们可以使用 switch,根据 amount 字段,来生成新的字段 discount

  1. const $ = db.command.aggregate
  2. db.collection('items').aggregate()
  3. .project({
  4. name: 1,
  5. discount: $.switch({
  6. branches: [
  7. { case: $.gt(['$amount', 250]), then: 0.8 },
  8. { case: $.gt(['$amount', 150]), then: 0.9 }
  9. ],
  10. default: 1
  11. })
  12. })
  13. .end()

输出如下:

  1. { "_id": "0", "name": "item-a", "discount": 1 }
  2. { "_id": "1", "name": "item-b", "discount": 0.9 }
  3. { "_id": "2", "name": "item-c", "discount": 0.8 }