Para agentes de IA: um índice de documentação está disponível em https://www.mongodb.com/pt-br/docs/llms.txt — as versões de markdown de todas as páginas estão disponíveis anexando .md a qualquer caminho de URL.
Menu Docs

$bsonSize (operador de expressão )

$bsonSize

Returns the size in bytes of a given document (i.e. bsontype Object) when encoded as BSON. You can use $bsonSize as an alternative to the bsonSize() method.

$bsonSize tem a seguinte sintaxe:

{ $bsonSize: <object> }

O argumento pode ser qualquer expressão válida, desde que resolva para um objeto ou null. Para mais informações sobre expressões, consulte Expressões.

Se o argumento for um objeto, a expressão retornará o tamanho do objeto em bytes quando o objeto for codificado como BSON.

Se o argumento for null, a expressão retornará null.

If the argument resolves to a data type other than an object or null, $bsonSize errors.

In mongosh, create a sample collection named employees with the following documents:

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."
}
}
]);

A seguinte aggregation projects:

  • O campo name

  • The object_size field, which uses $bsonSize to return the size of the document in bytes. The $$ROOT variable references the document currently being processed by the pipeline. To learn more about variables in the aggregation pipeline, see Variables in Aggregation Expressions.

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

A operação retorna o seguinte resultado:

{ "_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 }

O pipeline a seguir retorna o tamanho combinado de todos os documentos na collection employees:

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

Quando você especifica um $group _id valor de nullou qualquer outro valor constante, o estágio $group calcula os valores acumulados para todos os documentos de entrada como um todo.

The operation uses the $sum operator to calculate the combined $bsonSize of each document in the collection. The $$ROOT variable references the document currently being processed by the pipeline. To learn more about variables in the aggregation pipeline, see Variables in Aggregation Expressions.

A operação retorna o seguinte resultado:

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

Dica

O pipeline a seguir retorna o documento com o maior campo current_task em bytes:

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 }
])
Primeira etapa

O primeiro estágio do pipeline projects :

  • O campo name

  • The task_object_size field, which uses $bsonSize to return the size of the document's current_task field in bytes.

Este estágio produz os seguintes documentos para o próximo estágio:

{ "_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 }
Segunda etapa

O segundo estágio sorts os documentos por task_object_size em ordem decrescente.

Este estágio produz os seguintes documentos para o próximo estágio:

{ "_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 }
Terceiro estágio

O terceiro estágio limits os documentos de saída para retornar apenas o documento que aparece primeiro na ordem de classificação:

{ "_id" : 2, "name" : "Bob", "task_object_size" : 152 }
Avalie esta página