db.command.aggregate.indexOfCP
1. Operator Description
Description: Searches for a substring in a target string and returns the code point
index (starting from 0) of the first occurrence in UTF-8
. If the substring does not exist, returns -1.
Declaration: db.command.aggregate.indexOfCP([<target string expression>, <substring expression>, <start position expression>, <end position expression>])
Notes:
A
code point
is a "code position", also known as an "encoding position". Here it specifically refers to the code points in theUnicode
standard, ranging from 0 (hexadecimal) to 10FFFF (hexadecimal).
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | <Array>Expression | Required | Array of aggregate expressions, with the meaning of each element as follows |
Below are the detailed descriptions of the 4 expressions:
Expression | Description |
---|---|
Target String Expression | Any expression that can be resolved to a string |
Substring Expression | Any expression that can be resolved to a string |
Start Position Expression | Any expression that can be resolved to a non-negative integer |
End Position Expression | Any expression that can be resolved to a non-negative integer |
3. Sample Code
Suppose the collection students
contains the following records:
{ "firstName": "Yuanxin", "group": "a", "lastName": "Dong", "score": 84 }
{ "firstName": "Weijia", "group": "a", "lastName": "Wang", "score": 96 }
{ "firstName": "Chengxi", "group": "b", "lastName": "Li", "score": 80 }
Using indexOfCP
to find the position of the character "a"
in the field firstName
:
// 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,
aStrIndex: $.indexOfCP(['$firstName', 'a'])
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "aStrIndex": 2 }
{ "aStrIndex": 5 }
{ "aStrIndex": -1 }