Skip to main content

db.command.aggregate.min

1. Operator Description

Function: Returns the minimum value in a set of numbers.

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

2. Operator Parameters

FieldTypeRequiredDescription
-ExpressionRequiredAn expression is a string in the form of $ + specified field.

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 min, you can calculate the lowest score in different groups (group). 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',
minScore: $.min('$score')
})
.end()
console.log(res.data)
}

The returned data result is as follows:

{ "_id": "b", "minScore": 80 }
{ "_id": "a", "minScore": 84 }