View a markdown version of this page

$bsonSize - Amazon DocumentDB

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

$bsonSize

8.0.1 版中的新增内容。

当编码为 BSON 时,Amazon DocumentDB 中的$bsonSize运算符以字节为单位返回文档的大小。

参数

  • expression:解析为文档或对象的表达式。

示例(MongoDB Shell)

以下示例说明如何使用$bsonSize运算符返回每个文档的 BSON 大小。

创建示例文档

db.items.insertMany([ {_id: 1, name: "a", tags: ["x"]}, {_id: 2, name: "ab", tags: ["x", "y", "z"]}, {_id: 3, name: "abc", tags: []} ]);

查询示例

db.items.aggregate([ { $project: { docSize: { $bsonSize: "$$ROOT" } } } ]);

输出

[ {_id: 1, docSize: 46}, {_id: 2, docSize: 65}, {_id: 3, docSize: 39} ]
注意

确切的大小取决于文档字段的 BSON 编码。

代码示例

要查看使用$bsonSize运算符的代码示例,请选择要使用的语言的选项卡:

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('items'); const result = await collection.aggregate([ { $project: { docSize: { $bsonSize: "$$ROOT" } } } ]).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['items'] result = list(collection.aggregate([ {'$project': {'docSize': {'$bsonSize': '$$ROOT'}}} ])) print(result) finally: client.close() example()