$strLenCP (aggregation)

在本页面

Definition

返回指定字符串中的 UTF-8 code points的数量。

$strLenCP具有以下运算符表达式语法

{ $strLenCP: <string expression> }

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

如果参数解析为值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

$strLenCP运算符计算指定字符串中代码点的数量。此行为不同于$strLenBytes运算符,后者对字符串中的字节数进行计数,其中每个字符使用一到四个字节。

Example

单字节和多字节字符集

名为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" : "寿司" }

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

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

该操作返回以下结果:

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

See also

$strLenBytes

首页