“文档” 菜单
文档首页
/
MongoDB Manual
/ / /

$substrCP(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$substrCP

返回字符串的子string 。 子字符串以指定的 UTF-8 代码点 (CP) 处的字符开头string 中指定的代码点数的索引(从零开始)。

$substrCP具有以下操作符表达式语法:

{ $substrCP: [ <string expression>, <code point index>, <code point count> ] }
字段
类型
说明
string expression
字符串

要从中提取子字符串的字符串。 string expression可以是任何有效的表达式,只要它解析为字符串即可。 有关表达式的更多信息,请参阅表达式。

如果参数解析为 null 值或引用了缺失的字段,$substrCP 会返回一个空字符串。

如果参数未解析为字符串或 null,也未引用缺失字段,则 $substrCP 将会返回错误。

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 ] }
"tér"
{ $substrCP: [ "cafétéria", 7, 3 ] }
"ia"
{ $substrCP: [ "cafétéria", 3, 1 ] }
"é"

$substrCP 操作符使用代码点提取子字符串。这种行为不同于 $substrBytes 操作符,后者按字节数提取子字符串,其中每个字符使用一到四个字节。

考虑包含以下文档的 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 值分为 yearSubstringquarterSubstring 两部分: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 集合:

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" }

提示

另请参阅:

← $substrBytes(聚合)

在此页面上