$bsonSize聚合运算符返回文档(如:bsontype对象)编码为BSON后的字节数,可以使用$bsonSize替代bsonSize()方法。
{ $bsonSize: <object> }
参数可以是任何能够被解析为对象或null的表达式。
BSON后的字节数null,表达式返回nullnull,则报错使用下面的命令创建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."
}
}
]);
下面的聚合输出两个字段:
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运算符对集合的每个文档的大小进行合并,$$ROOT变量引用管道处理的当前文档。
操作返回下面的结果:
{ "_id" : null, "combined_object_size" : 789 }
下面的聚合管道返回集合中current_task字段字节数最多的文档:
db.employees.aggregate([
// 阶段1
{ $project: { name: "$name", task_object_size: { $bsonSize: "$current_task" } } },
// 阶段2
{ $sort: { "task_object_size" : -1 } },
// 阶段3
{ $limit: 1 }
])
第一个阶段投影一下字段:
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 }
阶段2按照task_object_size字段,有大到小对文档进行排序,该阶段输出下面的文档到下一阶段:
{ "_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 }
阶段三对输出文档的数量进行限制,只返回排序后的第一个文档:
{ "_id" : 2, "name" : "Bob", "task_object_size" : 152 }