On this page
$substrCP (aggregation)
在本页面
Definition
$substrCP
- 返回字符串的子字符串。子字符串以字符串中指定的 UTF-8 代码点(CP)索引(从零开始)处的字符开头,用于指定的代码点数。
{ $substrCP: [ <string expression>, <code point index>, <code point count> ] }
Field | Type | Description |
---|---|---|
string expression |
string | 从中提取子字符串的字符串。 string expression 可以是任何有效的expression,只要它可以解析为字符串即可。有关表达式的更多信息,请参见Expressions。 |
如果参数解析为值null
或引用了缺少的字段,则$substrCP返回空字符串。
如果参数不解析为字符串或null
,也没有引用缺少的字段,则$substrCP返回错误。
| code point index
| number |表示子字符串的起点。 code point index
可以是任何有效的expression,只要它解析为非负整数即可。
| code point count
| number |可以是任何有效的expression,只要它解析为非负整数或可以表示为整数的数字(例如 2.0)即可。
Example | Results |
---|---|
{ $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 ] } |
"tér" |
{ $substrCP: [ "cafétéria", 7, 3 ] } |
"ia" |
{ $substrCP: [ "cafétéria", 3, 1 ] } |
"é" |
Behavior
$substrCP运算符使用代码点提取子字符串。此行为不同于$substrBytes运算符,后者按字节数提取子字符串,其中每个字符使用一到四个字节。
Example
单字节字符集
考虑包含以下文档的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
和quarterSubstring
。 quarterSubstring
字段表示在yearSubstring
之后的指定byte index
中的其余字符串。它是通过使用$strLenCP从字符串的长度减去byte index
来计算的。
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
的集合包含以下文档:
{ "_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" }
See also