db.command.aggregate.let
1. Operator Description
Feature: Define custom variables and use them in specified expressions, returning the result of the expression.
Syntax: db.command.aggregate.let({ vars: { <variable1>: <variable_expression>, <variable2>: <variable_expression>, ... }, in: <result_expression> })
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | Object | Yes | in the form of { vars: {xxx:xxx, ...}, in: xxx}, parameters are detailed below |
Parameter description:
Multiple variables can be defined in
vars, whose values are computed by
variable expressions. These defined variables are only accessible within the
result expressionin
in`.
When accessing custom variables in the in
result expression, prefix the variable name with a double dollar sign ($$
) and enclose it in quotes.
3. Sample Code
Suppose the records in the collection goods
representing products are as follows: price
represents the product price, discount
represents the product discount rate, and cost
represents the product cost.
{ "cost": -10, "discount": 0.95, "price": 100 }
{ "cost": -15, "discount": 0.98, "price": 1 }
{ "cost": -10, "discount": 1, "price": 10 }
Using let
, you can define and compute the actual sales price for each product and assign it to a custom variable priceTotal
. Finally, perform a sum operation on priceTotal
and cost
to obtain the profit for each product.
The code is as follows:
// 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('goods')
.aggregate()
.project({
profit: $.let({
vars: {
priceTotal: $.multiply(['$price', '$discount'])
},
in: $.sum(['$$priceTotal', '$cost'])
})
})
.end()
console.log(res.data)
}
The returned data result is as follows:
{ "profit": 85 }
{ "profit": -14.02 }
{ "profit": 0 }