MongoDB聚合运算符:$substrCP
$substrCP
聚合运算符返回字符串的子串,子串是从指定的UTF-8代码点索引位置开始并包含指定数量的字符,索引是从零开始。
语法
{
$substrCP: [ <string expression>, <code point index>, <code point count> ] }
参数字段
字段 | 类型 | 描述 |
---|---|---|
string expression |
字符串 | 被取子串的字符串,可以是任何合法的字符串表达式。如果表达式解析为空或引用的字段缺失返回空字符串;如果表达式不能解析为字符串、不为空或字段没有缺失,则返回错误 |
code point index |
数值 | 取子串开始的代码点索引位置,必须是非负数的表达式 |
code point count |
数值 | 可以是非负整数表达式或可以表示为整数的数字(例如 2.0) |
例如 | 结果 |
---|---|
{ $substrCP: [ "abcde", 1, 2 ] } |
"bc" |
{ $substrCP: [ "Hello World!", 6, 5 ] } |
"World" |
{ $substrCP: [ "cafétéria", 0, 5 ] } |
"cafét" |
{ $substrCP: [ "cafétéria", 5, 4 ] } |
"éria" |
{ $substrCP: [ "cafétéria", 7, 3 ] } |
"ia" |
{ $substrCP: [ "cafétéria", 3, 1 ] } |
"é" |
使用
$substrCP
运算符使用代码点来提取子字符串,这与 $substrBytes
运算符不同,后者按字节数提取子字符串,其中每个字符使用 1 到 4 个字节。
举例
单字节字符集
inventory
集合有下列文档:
{
"_id" : 1, "item" : "ABC1", "quarter": "13Q1", "description" : "product 1" }
{
"_id" : 2, "item" : "ABC2", "quarter": "13Q4", "description" : "product 2" }
{
"_id" :