View a markdown version of this page

$binarySize - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$binarySize

8.0.1 版中的新增内容。

Amazon DocumentDB 中的$binarySize运算符以字节为单位返回给定字符串或二进制数据值的大小。对于字符串值,这是 UTF-8 编码的字节数,而不是字符数。 Multi-byte 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()