Skip to main content

db.command.aggregate.concat

1. Operator Description

Function: Concatenates strings and returns the concatenated string.

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

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredExpressions in the array can be in the form of $ + specified field or regular strings, as long as they can be resolved to strings.

3. Sample Code

Suppose the collection students contains the following records:

{ "firstName": "Yuanxin", "group": "a", "lastName": "Dong", "score": 84 }
{ "firstName": "Weijia", "group": "a", "lastName": "Wang", "score": 96 }
{ "firstName": "Chengxi", "group": "b", "lastName": "Li", "score": 80 }

Using concat, you can concatenate the lastName and firstName fields to get the full name of each student:

// 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('students')
.aggregate()
.project({
_id: 0,
fullName: $.concat(['$firstName', ' ', '$lastName'])
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "fullName": "Yuanxin Dong" }
{ "fullName": "Weijia Wang" }
{ "fullName": "Chengxi Li" }