本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$strLenCP
Amazon DocumentDB 中的$strLenCP运算符用于确定以代码点为单位的字符串表达式的长度(Unicode 字符)。当你需要知道字符串中的字符数而不是字节数时,这很有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$strLenCP运算符来确定包含 Unicode 字符的字符串的长度。
创建示例文档
db.people.insertMany([
{ "_id": 1, "Desk": "Düsseldorf-BVV-021" },
{ "_id": 2, "Desk": "Munich-HGG-32a" },
{ "_id": 3, "Desk": "Cologne-ayu-892.50" },
{ "_id": 4, "Desk": "Dortmund-Hop-78" }
])
查询示例
db.people.aggregate([
{
$project: {
"Desk": 1,
"length": { $strLenCP: "$Desk" }
}
}
])
输出
{ "_id" : 1, "Desk" : "Düsseldorf-BVV-021", "length" : 18 }
{ "_id" : 2, "Desk" : "Munich-HGG-32a", "length" : 14 }
{ "_id" : 3, "Desk" : "Cologne-ayu-892.50", "length" : 18 }
{ "_id" : 4, "Desk" : "Dortmund-Hop-78", "length" : 15 }
请注意包含 Unicode 字符 (U) 的 “杜塞尔多夫-bvv-021” 字符串的长度测量值的差异。$strLenCP运算符正确计算 Unicode 字符数,而$strLenBytes运算符则计算字节数。
代码示例
要查看使用该$strLenCP命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
以下是在带有 MongoDB 驱动程序的 Node.js 应用程序中使用该$strLenCP运算符的示例:
const { MongoClient } = require('mongodb');
async function example() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const collection = db.collection('people');
const result = await collection.aggregate([
{
$project: {
"Desk": 1,
"length": { $strLenCP: "$Desk" }
}
}
]).toArray();
console.log(result);
await client.close();
}
example();
- Python
-
以下是在带 PyMongo 驱动程序的 Python 应用程序中使用$strLenCP运算符的示例:
from pymongo import MongoClient
def example():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client.test
collection = db.people
result = list(collection.aggregate([
{
'$project': {
"Desk": 1,
"length": { "$strLenCP": "$Desk" }
}
}
]))
print(result)
client.close()
example()