db.command.aggregate.stdDevSamp
1. Operator Description
Function: Calculates the sample standard deviation of the input values. If the input values represent the entire population of data, or do not generalize to a larger dataset, use db.command.aggregate.stdDevPop
instead.
Declaration: db.command.aggregate.stdDevSamp(<expression>)
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | Expression | Required | The expression is passed a specified field. stdDevSamp automatically ignores non-numeric values. If all values in the specified field are non-numeric, the result returns null . |
3. Sample Code
Suppose the collection students
contains the following records:
{ "score": 80 }
{ "score": 100 }
stdDevSamp
can be used to calculate the sample standard deviation of scores. 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('students')
.aggregate()
.group({
_id: null,
ageStdDev: $.stdDevSamp('$score')
})
.end()
console.log(res.data)
}
The returned data result is as follows:
{ "_id": null, "ageStdDev": 14.142135623730951 }
If a new record is added to the collection students
with its score
field being of type string
:
{ "score": "aa" }
When calculating the sample standard deviation with the above code, stdDevSamp
automatically ignores records whose type is not number
, and the returned result remains unchanged.