Skip to main content

db.command.aggregate.mod

1. Operator Description

Function: Performs a modulo operation and returns the remainder.

Declaration: db.command.aggregate.mod([dividend, divisor])

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredThe first number is the dividend, and the second number is the divisor. The parameters can be any expressions that resolve to numbers.

3. Sample Code

Suppose the collection shopping contains the following records:

{ _id: 1, bags: 3, items: 5 }
{ _id: 2, bags: 2, items: 8 }
{ _id: 3, bags: 5, items: 16 }

For each record, calculate the remainder of items divided by bags (items % bags).

// 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('shopping')
.aggregate()
.project({
overflow: $.mod(['$items', '$bags'])
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ _id: 1, log: 2 }
{ _id: 2, log: 0 }
{ _id: 3, log: 1 }