db.command.aggregate.cond
1. Operator Description
Function: Evaluates a Boolean expression and returns one of the two specified values.
Declaration:
Two forms
cond({ if: <Boolean expression>, then: <true value>, else: <false value> })cond([ <Boolean expression>, <true value>, <false value> ])
Notes:
In both forms, the three parameters (
if,then,else) are mandatory.
If the Boolean expression evaluates to true,
$condwill return<true value>; otherwise it will return<false value>
2. Operator Parameters
| Field | Type | Required | Description |
|---|---|---|---|
| - | Object or <Array>[any] | Required | two forms (as described in the declaration) |
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 cond 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;
exports.main = async (event, context) => {
const res = await db
.collection("items")
.aggregate()
.project({
name: 1,
discount: $.cond({
if: $.gte(["$amount", 200]),
then: 0.7,
else: 0.9,
}),
})
.end();
console.log(res.data);
};
The output is as follows:
{ "_id": "0", "name": "item-a", "discount": 0.9 }
{ "_id": "1", "name": "item-b", "discount": 0.7 }
{ "_id": "2", "name": "item-c", "discount": 0.7 }