0
点赞
收藏
分享

微信扫一扫

第8章 软件工程

酷子腿长一米八 2024-05-03 阅读 38

MongoDB聚合运算符:$strLenCP

$strLenCP聚合运算符返回指定字符串中 UTF-8 代码点的数量。

语法

{ $strLenCP: <string expression> }

<expression>为可解析为字符串的表达式,如果解析为null或引用了不存在的字段,返回错误。

使用

$strLenCP 运算符计算指定字符串中的代码点数量,这不同于 $strLenBytes 运算符,后者计算字符串中的字节数,其中每个字符使用 1 到 4 个字节。

返回
{ $strLenCP: "abcde" }5
{ $strLenCP: "Hello World!" }12
{ $strLenCP: "cafeteria" }9
{ $strLenCP: "cafétéria" }9
{ $strLenCP: "" }0
{ $strLenCP: "$€λG" }4
{ $strLenCP: "寿司" }2

举例

单字节和多字节字符集

使用下面的脚本创建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" : "寿司" }
 ]
)

下面的聚合使用 $strLenCP 运算符计算name的长度:

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 }
]
举报

相关推荐

0 条评论