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 }
]
相关推荐
童谣16 小时前
越华环保集团市级统筹申报数字化中台:政策校验与减排仿真一体化架构
数据库·架构
制造数据与AI践行者老蒋6 小时前
离谱!PromptTemplate 遇上 JSON,花括号直接引发解析战争
数据库·microsoft·json
中微极客6 小时前
用LangChain 0.3构建生产级RAG与Agent:从API集成到Streamlit部署
数据库·人工智能·langchain
吴声子夜歌6 小时前
MongoDB 4.x——并发优化
数据库·mongodb
不如语冰7 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
l1t9 小时前
DeepSeek总结的DuckLake 架构深度剖析-2
数据库·架构
YOU OU9 小时前
Redis事务
数据库·redis·缓存
数智化管理手记10 小时前
财务大数据怎么管住资金风险?财务大数据和财务数智化到底怎么结合?
大数据·网络·数据库·人工智能·数据挖掘
晓子文集10 小时前
Tushare接口文档:指数成分和权重(index_weight)
大数据·数据库·python·金融·量化投资
吴声子夜歌10 小时前
MongoDB 4.2——入门指南
数据库·mongodb