Docs HomeMongoDB Manual

$strLenCP (aggregation)

On this page本页内容

Definition定义

$strLenCP

Returns the number of UTF-8 code points in the specified string.返回指定字符串中UTF-8代码点的数目。

$strLenCP has the following operator expression syntax:具有以下运算符表达式语法

{ $strLenCP: <string expression> }

The argument can be any valid expression that resolves to a string.参数可以是解析为字符串的任何有效表达式

If the argument resolves to a value of null or refers to a missing field, $strLenCP returns an error.如果参数解析为null值或引用了缺失的字段,$strLenCP将返回错误。

Example示例Results结果
{ $strLenCP: "abcde" }5
{ $strLenCP: "Hello World!" }12
{ $strLenCP: "cafeteria" }9
{ $strLenCP: "cafétéria" }9
{ $strLenCP: "" }0
{ $strLenCP: "$€λA" }4
{ $strLenCP: "寿司" }2

Behavior行为

The $strLenCP operator counts the number of code points in the specified string. $strLenCP运算符统计指定字符串中的代码点数量。This behavior differs from the $strLenBytes operator that counts the number of bytes in the string, where each character uses between one and four bytes.此行为不同于统计字符串中字节数的$strLenBytes运算符,其中每个字符使用一到四个字节。

Example实例

Single-Byte and Multibyte Character Set单字节和多字节字符集

Create a food collection:创建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: "寿司" }
] )

The following example uses the $strLenCP operator to calculate the length of each name value:以下示例使用$strLenCP运算符来计算每个name值的length

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

Example output:示例输出:

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

See also: 另请参阅:

$strLenBytes