Skip to main content

db.command.aggregate.stdDevPop

1. Operator Description

Function: Returns the standard deviation of the values corresponding to a set of fields.

Declaration: db.command.aggregate.stdDevPop(<expression>)

2. Operator Parameters

FieldTypeRequiredDescription
-ExpressionRequiredThe expression is passed a specified field. The value of the specified field must be of type number; otherwise, the result returns null.

3. Sample Code

Suppose the collection students contains the following records: the scores of students in group a are 84 and 96, and the scores of students in group b are 80 and 100.

{ "group":"a", "score":84 }
{ "group":"a", "score":96 }
{ "group":"b", "score":80 }
{ "group":"b", "score":100 }

You can use stdDevPop to calculate the standard deviation of the scores for groups a and b respectively, to compare which group has more stable 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: '$group',
stdDev: $.stdDevPop('$score')
})
.end()
console.log(res.data)
}

The returned data result is as follows:

{ "_id": "b", "stdDev": 10 }
{ "_id": "a", "stdDev": 6 }