Skip to main content

db.command.aggregate.subtract

1. Operator Description

Description: Subtracts two numbers and returns the difference, subtracts two dates and returns the difference in milliseconds, or subtracts a number from a date and returns the resulting date.

Declaration: db.command.aggregate.subtract([expression1, expression2])

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredArray of aggregate expressions. The parameters can be any expressions that resolve to numbers or dates.

3. Sample Code

Suppose the collection scores contains the following records:

{ "_id": 1, "max": 10, "min": 1 }
{ "_id": 2, "max": 7, "min": 5 }
{ "_id": 3, "max": 6, "min": 6 }

Calculate the difference between max and min for each record.

// 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('scores')
.aggregate()
.project({
diff: $.subtract(['$max', '$min'])
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": 1, "diff": 9 }
{ "_id": 2, "diff": 2 }
{ "_id": 3, "diff": 0 }