定义
$substrCP返回字符串的子字符串。 子字符串从字符串中指定的 UTF-8 代码点(CP)索引(从零开始)处的字符开始,包含指定的代码点数量。
$substrCPhas the following operator expression syntax:{ $substrCP: [ <string expression>, <code point index>, <code point count> ] } 字段类型说明string expression字符串
要从中提取子字符串的字符串。
string expression可以是任何有效的表达式,只要它解析为字符串即可。 有关表达式的更多信息,请参阅表达式。If the argument resolves to a value of
nullor refers to a field that is missing,$substrCPreturns an empty string.If the argument does not resolve to a string or
nullnor refers to a missing field,$substrCPreturns an error.code point index数字
表示子串的起点。
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 ] }"é"
行为
The $substrCP operator uses the code points to extract the substring. This behavior differs from the $substrBytes operator which extracts the substring by the number of bytes, where each character uses between one and four bytes.
例子
单字节字符集
考虑包含以下文档的 inventory 集合:
db.inventory.insertMany( [ { _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 } ] )
The following operation uses the $substrCP operator to separate the quarter value into a yearSubstring and a quarterSubstring. The quarterSubstring field represents the rest of the string from the specified byte index following the yearSubstring. It is calculated by subtracting the byte index from the length of the string using $strLenCP.
db.inventory.aggregate( [ { $project: { item: 1, yearSubstring: { $substrCP: [ "$quarter", 0, 2 ] }, quarterSubstring: { $substrCP: [ "$quarter", 2, { $subtract: [ { $strLenCP: "$quarter" }, 2 ] } ] } } } ] )
操作返回以下结果:
{ _id: 1, item: "ABC1", yearSubstring: "13", quarterSubstring: "Q1" } { _id: 2, item: "ABC2", yearSubstring: "13", quarterSubstring: "Q4" } { _id: 3, item: "XYZ1", yearSubstring: "14", quarterSubstring: "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 值创建一个三字节的 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" }