Skip to main content

db.command.aggregate.switch

1. Operator Description

Function: Calculates and returns a value based on the given switch-case-default.

Declaration: db.command.aggregate.switch({ branches: [ case: <expression>, then: <expression>, case: <expression>, then: <expression>, ... ], default: <expression> })

2. Operator Parameters

FieldTypeRequiredDescription
-ObjectRequiredIn a switch-case-default statement, each expression can be any valid aggregation expression.

3. Sample Code

Suppose the collection items contains the following records:

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

We can use switch to generate a new field discount based on the amount field:

// Sample code in the Cloud Function environment
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: 'xxx'
})

const db = app.database()
const $ = db.command.aggregate
const _ = db.command

exports.main = async (event, context) => {
const res = await db
.collection('items')
.aggregate()
.project({
name: 1,
discount: $.switch({
branches: [
{ case: $.gt(['$amount', 250]), then: 0.8 },
{ case: $.gt(['$amount', 150]), then: 0.9 }
],
default: 1
})
})
.end()
console.log(res.data)
}

The output is as follows:

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