Skip to main content

db.command.aggregate.add

1. Operator Description

Function: Adds numbers together or adds numbers to a date. If one of the values in the array is a date, the other values are treated as milliseconds added to that date.

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

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredA string expression can be in the form of $ + specified field or a regular string, as long as it can be resolved to a string.

3. Sample Code

Suppose the collection staff contains the following records:

{ _id: 1, department: "x", sales: 5, engineer: 10, lastUpdate: ISODate("2019-05-01T00:00:00Z") }
{ _id: 2, department: "y", sales: 10, engineer: 20, lastUpdate: ISODate("2019-05-01T02:00:00Z") }
{ _id: 3, department: "z", sales: 20, engineer: 5, lastUpdate: ISODate("2019-05-02T03:00:00Z") }

Summing Numbers

The total number of people for each record can be calculated 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

exports.main = async (event, context) => {
const res = await db
.collection('staff')
.aggregate()
.project({
department: 1,
total: $.add(['$sales', '$engineer'])
})
.end()
console.log(res.data) // Print the aggregation result
}

The returned result is as follows:

{ _id: 1, department: "x", total: 15 }
{ _id: 2, department: "y", total: 30 }
{ _id: 3, department: "z", total: 25 }

Adding Date Values

The following operation can obtain the value of lastUpdate plus one hour 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

exports.main = async (event, context) => {
const res = await db
.collection('staff')
.aggregate()
.project({
department: 1,
lastUpdate: $.add(['$lastUpdate', 60 * 60 * 1000])
})
.end()
console.log(res.data) // Print the aggregation result
}

The returned result is as follows:

{ _id: 1, department: "x", lastUpdate: ISODate("2019-05-01T01:00:00Z") }
{ _id: 2, department: "y", lastUpdate: ISODate("2019-05-01T03:00:00Z") }
{ _id: 3, department: "z", lastUpdate: ISODate("2019-05-02T04:00:00Z") }