Skip to main content

db.command.aggregate.substrCP

1. Operator Description

Function: Returns a substring of specified length starting from a specified position in the string. The substring begins at the character corresponding to the specified UTF-8 byte index and extends for the specified number of bytes.

Declaration: db.command.aggregate.substrCP([<expression1>, <expression2>, <expression3>])

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredArray of aggregate expressions, with each expression detailed below

Parameter description:

expression1is any valid expression that can be resolved to a string, andexpression2andexpression3` are any valid expressions that can be resolved to numbers.

If expression2 is negative, the result returned is "".

If expression3 is negative, the result returned is a substring starting from the position specified by expression2 and including all subsequent characters.

3. Sample Code

Suppose the collection students contains the following records:

{ "name": "dongyuanxin", "nickname": "Xin Tan" }

Using substrCP to extract the first Chinese character from the nickname field value:

// 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('students')
.aggregate()
.project({
_id: 0,
firstCh: $.substrCP(['$nickname', 0, 1])
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "firstCh": "Xin" }