- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $binarySize (aggregation)
$binarySize (aggregation)¶
On this page
Definition¶
-
$binarySize
¶ New in version 4.4.
Returns the size of a given string or binary data value’s content in bytes.
$binarySize
has the following syntax:The argument can be any valid expression as long as it resolves to either a string or binary data value. For more information on expressions, see Expressions.
Behavior¶
The argument for $binarySize
must resolve to either:
- A string,
- A binary data value, or
- null.
If the argument is a string or binary data value, the expression returns the size of the argument in bytes.
If the argument is null
, the expression returns null
.
If the argument resolves to any other data type,
$binarySize
errors.
String Size Calculation¶
If the argument for $binarySize
is a string, the operator
counts the number of UTF-8 encoded bytes in a string where each character
may use between one and four bytes.
For example, US-ASCII characters are encoded using one byte. Characters with diacritic markings and additional Latin alphabetical characters (i.e. Latin characters outside of the English alphabet) are encoded using two bytes. Chinese, Japanese and Korean characters typically require three bytes, and other planes of unicode (emoji, mathematical symbols, etc.) require four bytes.
Consider the following examples:
Example | Results | Notes |
---|---|---|
5 |
Each character is encoded using one byte. | |
12 |
Each character is encoded using one byte. | |
9 |
Each character is encoded using one byte. | |
11 |
é is encoded using two bytes. |
|
0 |
Empty strings return 0. | |
7 |
€ is encoded using three bytes.
λ is encoded using two bytes. |
|
6 |
Each character is encoded using three bytes. |
Example¶
From the mongo
shell, create a sample collection named
images
with the following documents:
The following aggregation projects
:
- The
name
field - The
imageSize
field, which uses$binarySize
to return the size of the document’sbinary
field in bytes.
The operation returns the following result:
Find Largest Binary Data¶
The following pipeline returns the image with the largest binary data size:
- First Stage
The first stage of the pipeline
projects
:- The
name
field - The
imageSize
field, which usesbinarySize
to return the size of the document’sbinary
field in bytes.
This stage outputs the following documents to the next stage:
- The
- Second Stage
The second stage
sorts
the documents byimageSize
in descending order.This stage outputs the following documents to the next stage:
- Third Stage
The third stage
limits
the output documents to only return the document appearing first in the sort order:
See also