db.command.aggregate.pow
1. Operator Description
Function: Computes the power of a given base raised to an exponent.
Declaration: db.command.aggregate.pow([base, exponent])
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | <Array>Expression | Required | array of aggregate expressions |
3. Sample Code
Suppose the collection stats
contains the following records:
{ "_id": 1, "x": 2, "y": 3 }
{ "_id": 2, "x": 5, "y": 7 }
{ "_id": 3, "x": 10, "y": 20 }
Calculate the sum of squares of x
and y
:
// 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('stats')
.aggregate()
.project({
sumOfSquares: $.add([$.pow(['$x', 2]), $.pow(['$y', 2])])
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "_id": 1, "sumOfSquares": 13 }
{ "_id": 2, "sumOfSquares": 74 }
{ "_id": 3, "sumOfSquares": 500 }