Skip to main content

db.command.aggregate.avg

1. Operator Description

Function: Returns the average value of the specified field in a collection.

Declaration: db.command.aggregate.avg(expression)

2. Operator Parameters

FieldTypeRequiredDescription
-ExpressionRequiredBesides numeric constants, the value passed to avg can also be any expression that resolves to a number; it ignores non-numeric values.

3. Sample Code

Suppose the collection students contains the following records:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

Using avg, the average value of the score field across all records can be calculated:

// 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

exports.main = async (event, context) => {
const res = await db
.collection('students')
.aggregate()
.group({
_id: null,
average: $.avg('$score')
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": null, "average": 90 }