db.command.aggregate.sqrt
1. Operator Description
Function: Compute the square root.
Syntax: db.command.aggregate.sqrt([number])
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | <Array>Expression | Required | The parameter can be any expression that resolves to a non-negative number. |
3. Sample Code
Suppose the right triangle collection triangle
contains the following records:
{ "_id": 1, "x": 2, "y": 3 }
{ "_id": 2, "x": 5, "y": 7 }
{ "_id": 3, "x": 10, "y": 20 }
Suppose x
and y
are the two legs of a right triangle, then calculate the length of the hypotenuse:
// 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('triangle')
.aggregate()
.project({
len: $.sqrt([$.add([$.pow(['$x', 2]), $.pow(['$y', 2])])])
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "_id": 1, "len": 3.605551275463989 }
{ "_id": 2, "len": 8.602325267042627 }
{ "_id": 3, "len": 22.360679774997898 }