Skip to main content

db.command.aggregate.split

1. Operator Description

Function: Splits an array by a separator, removes the separator, and returns an array of substrings. If the string cannot be split by the separator, returns the original string as the single element of the array.

Declaration: db.command.aggregate.split([string expression, delimiter expression])

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredThe string expression and delimiter expression can be any form of expression, as long as they can be resolved to strings.

3. Sample Code

Suppose the collection students contains the following records:

{ "birthday": "1999/12/12" }
{ "birthday": "1998/11/11" }
{ "birthday": "1997/10/10" }

Using the split operator, split the value of the birthday field in each record into an array, with each array consisting of three elements representing the year, month, and day:

// 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,
birthday: $.split(['$birthday', '/'])
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "birthday": [ "1999", "12", "12" ] }
{ "birthday": [ "1998", "11", "11" ] }
{ "birthday": [ "1997", "10", "10" ] }