Skip to main content

db.command.aggregate.reduce

1. Operator Description

Function: Similar to JavaScript's reduce method, applies an expression to each element of an array and reduces them into a single element.

Declaration: db.command.aggregate.reduce({ input: array, initialValue: expression, in: expression })

2. Operator Parameters

FieldTypeRequiredDescription
inputExpressionRequiredThe input array, which can be any expression that resolves to an array.
initialValueExpressionRequiredInitial value
inExpressionRequiredAn expression applied to each element. Two variables are available in in: value represents the accumulated value, and this represents the current array element.

3. Sample Code

Simple String Concatenation

Suppose the collection player contains the following records:

{ "_id": 1, "fullname": [ "Stephen", "Curry" ] }
{ "_id": 2, "fullname": [ "Klay", "Thompsom" ] }

Get the full names of all players and prefix them with Player:.

// 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('player')
.aggregate()
.project({
info: $.reduce({
input: '$fullname',
initialValue: 'Player:',
in: $.concat(['$$value', ' ', '$$this'])
})
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": 1, "info": "Player: Stephen Curry" }
{ "_id": 2, "info": "Player: Klay Thompson" }

Get the full names of all players without any prefix.

const $ = db.command.aggregate
db.collection('player')
.aggregate()
.project({
name: $.reduce({
input: '$fullname',
initialValue: '',
in: $.concat([
'$$value',
$.cond({
if: $.eq(['$$value', '']),
then: '',
else: ' '
}),
'$$this'
])
})
})
.end()

The returned result is as follows:

{ "_id": 1, "name": "Stephen Curry" }
{ "_id": 2, "name": "Klay Thompson" }