db.command.aggregate.substr
1. Operator Description
Function: Returns a substring of a specified length starting from a specified position in the string. It is an alias for db.command.aggregate.substrBytes
, and the latter is recommended.
Declaration: db.command.aggregate.substr([<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 }
Using substr
, the year, month, and day information can be extracted 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: $.substr(['$birthday', 0, 4]),
month: $.substr(['$birthday', 5, 2]),
day: $.substr(['$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" }