On this page本页内容
$bsonSize
¶New in version 4.4.版本4.4中的新功能。
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 Object.bsonSize() method.
$bsonSize
has the following syntax:语法如下所示:
The argument can be any valid expression as long as it resolves to either an object or null
. For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
If the argument is an object, the expression returns the size of the object in bytes when the object is encoded as BSON.
If the argument is null
, the expression returns null
.
If the argument resolves to a data type other than an object or null
, $bsonSize
errors.
From the mongo
shell, create a sample collection named employees
with the following documents:
The following aggregation projects
:
name
fieldobject_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.The operation returns the following result:操作返回以下结果:
The following pipeline returns the combined size of all of the documents in the employees
collection:
When you specify an $group
_id value of null
, or any other constant value, the $group
stage calculates accumulated values for all the input documents as a whole.
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.
The operation returns the following result:操作返回以下结果:
The following pipeline returns the document with the largest current_task
field in bytes:
The first stage of the pipeline projects
:
name
fieldtask_object_size
field, which uses $bsonSize
to return the size of the document’s current_task
field in bytes.This stage outputs the following documents to the next stage:
The second stage sorts
the documents by task_object_size
in descending order.
This stage outputs the following documents to the next stage:
The third stage limits
the output documents to only return the document appearing first in the sort order:
See also参阅