db.command.aggregate.sum
1. Operator Description
Function: Calculates and returns the sum of all numeric values in a set of fields.
Declaration: db.command.aggregate.sum(<expression>)
2. Operator Parameters
| Field | Type | Required | Description |
|---|---|---|---|
| - | Expression | Required | aggregate expression |
Parameter description:
The expression can be passed a specified field or a list of specified fields. sum automatically ignores non-numeric values. If all values under the field are non-numeric, the result returns 0. If a numeric constant is passed, it is treated as if all records have that constant value for the field. During aggregation, the values are summed, and the final value is the number of input records multiplied by the constant.
3. Sample Code
Suppose the records in the collection goods representing products are as follows: price represents product sales, and cost represents product cost.
{ "cost": -10, "price": 100 }
{ "cost": -15, "price": 1 }
{ "cost": -10, "price": 10 }
Individual Field
Using sum, you can calculate the total sales of all products. 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()
.group({
_id: null,
totalPrice: $.sum('$price')
})
.end()
console.log(res.data)
}
The returned data result is as follows: Sales is 111
{ "_id": null, "totalPrice": 111 }
Field List
To calculate the total profit of all products, you need to add the cost and price for each record to obtain the profit of the corresponding product. Then calculate the total profit of all products.
Using sum, 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()
.group({
_id: null,
totalProfit: $.sum($.sum(['$price', '$cost']))
})
.end()
console.log(res.data)
}
The returned data result is as follows: total profit is 76
{ "_id": null, "totalProfit": 76 }