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" : 3, "item" : "XYZ1", "quarter": "14Q2", "description" : null }
下面的聚合操作使用 $substrCP
运算符将quarter
字段拆分拆分为yearSubstring
和quarterSubstrin
字段。其中quarterSubstring
字段表示来自yearSubstring
后面的指定字节索引的字符串的其余部分,通过使用$strLenCP
从字符串长度中减去字节索引来计算的。:
db.inventory.aggregate(
[
{
$project: {
item: 1,
yearSubstring: { $substrCP: [ "$quarter", 0, 2 ] },
quarterSubtring: {
$substrCP: [
"$quarter", 2, { $subtract: [ { $strLenCP: "$quarter" }, 2 ] }
]
}
}
}
]
)
操作返回下面的结果:
{ "_id" : 1, "item" : "ABC1", "yearSubstring" : "13", "quarterSubtring" : "Q1" }
{ "_id" : 2, "item" : "ABC2", "yearSubstring" : "13", "quarterSubtring" : "Q4" }
{ "_id" : 3, "item" : "XYZ1", "yearSubstring" : "14", "quarterSubtring" : "Q2" }
单字节和多字节字符集
使用下面的脚本创建food
字符集:
db.food.insertMany(
[
{ "_id" : 1, "name" : "apple" },
{ "_id" : 2, "name" : "banana" },
{ "_id" : 3, "name" : "éclair" },
{ "_id" : 4, "name" : "hamburger" },
{ "_id" : 5, "name" : "jalapeño" },
{ "_id" : 6, "name" : "pizza" },
{ "_id" : 7, "name" : "tacos" },
{ "_id" : 8, "name" : "寿司sushi" }
]
)
下面的例子使用$substrCP
运算符从name
字段创建一个3个字节的menuCode
字段:
db.food.aggregate(
[
{
$project: {
"name": 1,
"menuCode": { $substrCP: [ "$name", 0, 3 ] }
}
}
]
)
操作返回下面的结果:
{ "_id" : 1, "name" : "apple", "menuCode" : "app" }
{ "_id" : 2, "name" : "banana", "menuCode" : "ban" }
{ "_id" : 3, "name" : "éclair", "menuCode" : "écl" }
{ "_id" : 4, "name" : "hamburger", "menuCode" : "ham" }
{ "_id" : 5, "name" : "jalapeño", "menuCode" : "jal" }
{ "_id" : 6, "name" : "pizza", "menuCode" : "piz" }
{ "_id" : 7, "name" : "tacos", "menuCode" : "tac" }
{ "_id" : 8, "name" : "寿司sushi", "menuCode" : "寿司s" }