文档菜单
文档首页
/
MongoDB 手册
/ / /

$bsonSize(聚合)

本页内容

  • 定义
  • 行为
  • 示例
$bsonSize

返回给定文档的大小(即bsontype Object),当以BSON 编码时。您可以使用

$bsonSize 作为 bsonSize() 方法的替代。

{ $bsonSize: <object> }

$bsonSize 的语法如下

行为

如果参数是对象,表达式返回对象以 BSON 编码时的字节大小。

如果参数是 null,表达式返回 null

mongosh 中,创建一个名为 employees 的示例集合,包含以下文档

db.employees.insertMany([
{
"_id": 1,
"name": "Alice", "email": "alice@company.com", "position": "Software Developer",
"current_task": {
"project_id": 1,
"project_name": "Aggregation Improvements",
"project_duration": 5,
"hours": 20
}
},
{
"_id": 2,
"name": "Bob", "email": "bob@company.com", "position": "Sales",
"current_task": {
"project_id": 2,
"project_name": "Write Blog Posts",
"project_duration": 2,
"hours": 10,
"notes": "Progress is slow. Waiting for feedback."
}
},
{
"_id": 3,
"name": "Charlie", "email": "charlie@company.com", "position": "HR (On Leave)",
"current_task": null
},
{
"_id": 4,
"name": "Dianne", "email": "diane@company.com", "position": "Web Designer",
"current_task": {
"project_id": 3,
"project_name": "Update Home Page",
"notes": "Need to scope this project."
}
}
]);

以下聚合 projects:

  • 字段 name

  • 字段 object_size,它使用 $bsonSize 返回文档的字节数。变量 $$ROOT 指的是当前正在处理管道中的文档。有关聚合管道中变量的更多信息,请参阅聚合表达式中的变量。

db.employees.aggregate([
{
"$project": {
"name": 1,
"object_size": { $bsonSize: "$$ROOT" }
}
}
])

该操作返回以下结果

{ "_id" : 1, "name" : "Alice", "object_size" : 222 }
{ "_id" : 2, "name" : "Bob", "object_size" : 248 }
{ "_id" : 3, "name" : "Charlie", "object_size" : 112 }
{ "_id" : 4, "name" : "Dianne", "object_size" : 207 }

以下管道返回 employees 集合中所有文档的合并大小

db.employees.aggregate([
{
"$group": {
"_id": null,
"combined_object_size": { $sum: { $bsonSize: "$$ROOT" } }
}
}
])

当指定 $group _id 值为 null 或任何其他常量值时,$group 阶段将计算所有输入文档的累积值。

该操作使用 $sum 操作符计算集合中每个文档的合并 $bsonSize。变量 $$ROOT 指的是当前正在处理管道中的文档。有关聚合管道中变量的更多信息,请参阅聚合表达式中的变量。

该操作返回以下结果

{ "_id" : null, "combined_object_size" : 789 }

提示

另请参阅

以下管道返回具有最大 current_task 字段(以字节为单位)的文档

db.employees.aggregate([
// First Stage
{ $project: { name: "$name", task_object_size: { $bsonSize: "$current_task" } } },
// Second Stage
{ $sort: { "task_object_size" : -1 } },
// Third Stage
{ $limit: 1 }
])
第一阶段

管道的第一阶段使用 projects:

  • 字段 name

  • task_object_size 字段,使用 $bsonSize 返回文档 current_task 字段的字节大小。

此阶段将以下文档输出到下一阶段

{ "_id" : 1, "name" : "Alice", "task_object_size" : 109 }
{ "_id" : 2, "name" : "Bob", "task_object_size" : 152 }
{ "_id" : 3, "name" : "Charlie", "task_object_size" : null }
{ "_id" : 4, "name" : "Dianne", "task_object_size" : 99 }
第二阶段

第二阶段使用 sorts 按照降序对文档进行排序。

此阶段将以下文档输出到下一阶段

{ "_id" : 2, "name" : "Bob", "task_object_size" : 152 }
{ "_id" : 1, "name" : "Alice", "task_object_size" : 109 }
{ "_id" : 4, "name" : "Dianne", "task_object_size" : 99 }
{ "_id" : 3, "name" : "Charlie", "task_object_size" : null }
第三阶段

第三阶段使用 limits 限制输出文档,仅返回排序顺序中出现的第一个文档

{ "_id" : 2, "name" : "Bob", "task_object_size" : 152 }

返回

$bottomN

本页内容