db.command.aggregate.substrBytes
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.substrBytes([<expression1>, <expression2>, <expression3>])
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | <Array>Expression | Required | Array of aggregate expressions, with each expression detailed below |
Parameter description:
expression1is any valid expression that can be resolved to a string, and
expression2and
expression3` 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:
{ "birthday": "1999/12/12", "firstName": "Yuanxin", "group": "a", "lastName": "Dong", "score": 84 }
{ "birthday": "1998/11/11", "firstName": "Weijia", "group": "a", "lastName": "Wang", "score": 96 }
{ "birthday": "1997/10/10", "firstName": "Chengxi", "group": "b", "lastName": "Li", "score": 80 }
You can use substrBytes
to extract the year, month, and day information from birthday
. The code is as follows:
// 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,
year: $.substrBytes(['$birthday', 0, 4]),
month: $.substrBytes(['$birthday', 5, 2]),
day: $.substrBytes(['$birthday', 8, -1])
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "day": "12", "month": "12", "year": "1999" }
{ "day": "11", "month": "11", "year": "1998" }
{ "day": "10", "month": "10", "year": "1997" }