- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $bsonSize (aggregation)
$bsonSize (aggregation)¶
On this page
Definition¶
-
$bsonSize¶ New in version 4.4.
Returns the size in bytes of a given document (i.e. bsontype
Object) when encoded as BSON. You can use$bsonSizeas an alternative to the Object.bsonSize() method.$bsonSizehas 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.
Behavior¶
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.
Examples¶
Return Sizes of Documents¶
From the mongo shell, create a sample collection named
employees with the following documents:
The following aggregation projects:
- The
namefield - The
object_sizefield, which uses$bsonSizeto return the size of the document in bytes. The$$ROOTvariable 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:
Return Combined Size of All Documents in a Collection¶
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:
Return Document with Largest Specified Field¶
The following pipeline returns the document with the largest
current_task field in bytes:
- First Stage
The first stage of the pipeline
projects:- The
namefield - The
task_object_sizefield, which uses$bsonSizeto return the size of the document’scurrent_taskfield in bytes.
This stage outputs the following documents to the next stage:
- The
- Second Stage
The second stage
sortsthe documents bytask_object_sizein descending order.This stage outputs the following documents to the next stage:
- Third Stage
The third stage
limitsthe output documents to only return the document appearing first in the sort order:
See also