Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$strLenBytes
Amazon DocumentDB 中的$strLenBytes运算符用于确定字符串的长度(以字节为单位)。当您需要了解字符串字段的存储大小时,这很有用,尤其是在处理每个字符可能使用超过一个字节的 Unicode 字符时。
参数
示例(MongoDB 外壳)
此示例演示如何使用$strLenBytes运算符计算字符串字段的长度(以字节为单位)。
创建示例文档
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": { $strLenBytes: "$Desk" }
}
}
])
输出
{ "_id" : 1, "Desk" : "Düsseldorf-BVV-021", "length" : 19 }
{ "_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 }
请注意,“Düseldorf-bvv-021” 字符串的长度为 19 字节,这与码点数 (18) 不同,因为 Unicode 字符 “U” 占用 2 个字节。
代码示例
要查看使用该$strLenBytes命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
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": { $strLenBytes: "$Desk" }
}
}
]).toArray();
console.log(result);
client.close();
}
example();
- Python
-
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": { "$strLenBytes": "$Desk" }
}
}
]))
print(result)
client.close()
example()