Skip to main content

db.command.aggregate.strLenBytes

1. Operator Description

Function: Calculates and returns the number of bytes in the specified string under utf-8 encoding.

Declaration: db.command.aggregate.strLenBytes(<expression>)

2. Operator Parameters

FieldTypeRequiredDescription
-ExpressionRequiredaggregate expression that can be resolved to a string

3. Sample Code

Suppose the collection students contains the following records:

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

Use strLenBytes to calculate the byte length of the values corresponding to the name and nickname fields:

// 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,
nameLength: $.strLenBytes('$name'),
nicknameLength: $.strLenBytes('$nickname')
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "nameLength": 11, "nicknameLength": 6 }