View a markdown version of this page

$binarySize - Amazon DocumentDB

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

$binarySize

8.0.1 版的新功能。

Amazon DocumentDB 中的$binarySize運算子會傳回指定字串或二進位資料值的位元組大小。對於字串值,這是 UTF-8 編碼的位元組計數,而不是字元計數。多位元組 UTF-8 字元 (例如重音字元或 CJK 字元) 會產生大於字串中字元數的位元組計數。

參數

  • expression:解析為字串或二進位資料值的表達式。

範例 (MongoDB Shell)

下列範例示範如何使用 $binarySize運算子傳回字串欄位的位元組大小。

建立範例文件

db.docs.insertMany([ {_id: 1, content: "hello"}, {_id: 2, content: "Amazon DocumentDB"}, {_id: 3, content: ""} ]);

查詢範例

db.docs.aggregate([ { $project: { size: { $binarySize: "$content" } } } ]);

輸出

[ {_id: 1, size: 5}, {_id: 2, size: 17}, {_id: 3, size: 0} ]

程式碼範例

若要檢視使用 $binarySize 運算子的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); const collection = db.collection('docs'); const result = await collection.aggregate([ { $project: { size: { $binarySize: "$content" } } } ]).toArray(); console.log(result); } finally { await 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') try: db = client['test'] collection = db['docs'] result = list(collection.aggregate([ {'$project': {'size': {'$binarySize': '$content'}}} ])) print(result) finally: client.close() example()