$strLenBytes - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$strLenBytes

Amazon DocumentDB 中的$strLenBytes運算子用於判斷字串的長度,以位元組為單位。當您需要了解字串欄位的儲存大小時,特別是在處理每個字元可能使用超過一個位元組的 Unicode 字元時,此功能非常有用。

參數

  • expression:要計算 長度的字串表達式。

範例 (MongoDB Shell)

此範例示範如何使用 $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üsseldorf-BVV-021」字串的長度為 19 個位元組,不同於程式碼點 (18) 的數量,因為 Unicode 字元「Ü」佔用 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()