$strLenCP(聚合)
定义
行为
$strLenCP
操作符计算指定字符串中的代码点数。此行为不同于计算字符串中字节数的 $strLenBytes
操作符,其中每个字符使用 1 到 4 个字节。
例子
单字节和多字节字符集
创建一个 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
值的 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 } ]