Skip to main content

db.command.aggregate.divide

1. Operator Description

Function: Takes the dividend and divisor, and calculates the quotient.

Declaration: db.command.aggregate.divide([<dividend expression>, <divisor expression>])

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredThe expression can be any expression that resolves to a number.

3. Sample Code

Suppose the collection railroads contains the following records:

{ _id: 1, meters: 5300 }
{ _id: 2, meters: 64000 }
{ _id: 3, meters: 130 }

The value after converting each number to kilometers can be obtained 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('railroads')
.aggregate()
.project({
km: $.divide(['$meters', 1000])
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ _id: 1, km: 5.3 }
{ _id: 2, km: 64 }
{ _id: 3, km: 0.13 }