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

$strLenBytes(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$strLenBytes

返回指定字符串中 UTF-8 编码的字节数。

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

{ $strLenBytes: <string expression> }

该参数可以是任何有效的表达式,只要它解析为字符串即可。 有关表达式的更多信息,请参阅表达式。

如果参数解析为 null 的值或指向缺失的字段,$strLenBytes 返回错误。

$strLenBytes操作符计算string中 UTF-8 编码的字节数,其中每个字符可能使用 1 到 4 个字节。

例如,US-ASCII 字符使用一个字节进行编码。 带有变音符号和附加拉丁字母字符的字符(即 英语字母表以外的拉丁字符)使用两个字节进行编码。 中文、日文和韩文字符通常需要三个字节,而其他平面的 unicode(表情符号、数学符号等)需要四个字节。

$strLenBytes操作符与$strLenCP 操作符不同,后者计算 代码点 在指定字符串中,无论每个字符使用多少字节。

例子
结果
注意
{ $strLenBytes: "abcde" }
5
每个字符使用一个字节进行编码。
{ $strLenBytes: "Hello World!" }
12
每个字符使用一个字节进行编码。
{ $strLenBytes: "cafeteria" }
9
每个字符使用一个字节进行编码。
{ $strLenBytes: "cafétéria" }
11
é 使用两个字节进行编码。
{ $strLenBytes: "" }
0
空字符串返回 0。
{ $strLenBytes: "$€λG" }
7
使用三个字节进行编码。 λ使用两个字节进行编码。
{ $strLenBytes: "寿司" }
6
每个字符使用三个字节进行编码。

使用以下文档创建 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" : "寿司" }
]
)

以下操作使用$strLenBytes操作符计算每个name值的length

db.food.aggregate(
[
{
$project: {
"name": 1,
"length": { $strLenBytes: "$name" }
}
}
]
)

操作返回以下结果:

{ "_id" : 1, "name" : "apple", "length" : 5 }
{ "_id" : 2, "name" : "banana", "length" : 6 }
{ "_id" : 3, "name" : "éclair", "length" : 7 }
{ "_id" : 4, "name" : "hamburger", "length" : 9 }
{ "_id" : 5, "name" : "jalapeño", "length" : 9 }
{ "_id" : 6, "name" : "pizza", "length" : 5 }
{ "_id" : 7, "name" : "tacos", "length" : 5 }
{ "_id" : 8, "name" : "寿司", "length" : 6 }

带有_id: 3_id: 5的文档各包含一个变音符号(分别为éñ ),需要两个字节进行编码。 带有_id: 8的文档包含两个日文字符,每个字符使用三个字节进行编码。 对于具有_id: 3_id: 5_id: 8的文档,这使得length大于name中的字符数。

提示

另请参阅:

← $strcasecmp(聚合)

在此页面上