MongoDB聚合运算符:$strLenCP

MongoDB聚合运算符:$strLenCP

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

语法

js 复制代码
{ $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集合:

js 复制代码
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的长度:

js 复制代码
db.food.aggregate( [
   {
      $project: {
         name: 1,
         length: { $strLenCP: "$name" }
      }
   }
] )

操作返回下面的结果:

js 复制代码
[
   { _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 }
]
相关推荐
武子康1 小时前
Java-171 Neo4j 备份与恢复 + 预热与执行计划实战
java·开发语言·数据库·性能优化·系统架构·nosql·neo4j
无敌最俊朗@2 小时前
02-SQLite 为了防止多人同时乱写,把整个数据库文件“当一本账本加锁”
jvm·数据库·oracle
小坏讲微服务2 小时前
MaxWell中基本使用原理 完整使用 (第一章)
大数据·数据库·hadoop·sqoop·1024程序员节·maxwell
赵渝强老师2 小时前
【赵渝强老师】MySQL集群解决方案
数据库·mysql
jason.zeng@15022073 小时前
my.cnf详解
运维·数据库·adb
百***62853 小时前
MySQL 常用 SQL 语句大全
数据库·sql·mysql
2501_915918413 小时前
移动端 HTTPS 抓包实战,多工具组合分析与高效排查指南
数据库·网络协议·ios·小程序·https·uni-app·iphone
百***6973 小时前
MySQL数据库(SQL分类)
数据库·sql·mysql
只因在人海中多看了你一眼3 小时前
B.40.5.1-数据库基础与核心原理
数据库
2503_928411564 小时前
11.11 Express-generator和文件上传和身份认证
数据库·node.js·express