From MongoDB 4.4, you can use the $binarySize
aggregation pipeline operator to return the size of a given string or binary data value’s content in bytes.
It accepts any valid expression as long as it resolves to either a string or binary data value. The argument can also be null
, in which case, $binarySize
returns null
.
Example
Suppose we have a collection called posts
with the following document:
{ "_id" : 1, "title" : "Hello World!", "body" : "This is a test post for the purposes of testing", "tags" : [ "html", "css", "sql", "xml" ], "status" : null }
We can use the $binarySize
operator to check the size of various fields.
Example:
db.posts.aggregate([
{
$project: {
"titleSize": { $binarySize: "$title" },
"bodySize": { $binarySize: "$body" }
}
}
])
Result:
{ "_id" : 1, "titleSize" : 12, "bodySize" : 47 }
In this case, we return the binary size of the title
field and the body
field.
Null Values
If the specified field’s value is null
, the $binarySize
operator will return null
.
Example:
db.posts.aggregate([
{
$project: {
"statusSize": { $binarySize: "$status" }
}
}
])
Result:
{ "_id" : 1, "statusSize" : null }
In this case, the status
field in our document is null
, and so $binarySize
returned null
.
Wrong Data Types
As mentioned, $binarySize
accepts any valid expression as long as it resolves to either a string, a binary data value, or null
.
Here’s an example of what happens if you provide an expression that resolves to a different BSON type:
db.posts.aggregate([
{
$project: {
"tagsSize": { $binarySize: "$tags" }
}
}
])
Result:
Error: command failed: { "ok" : 0, "errmsg" : "$binarySize requires a string or BinData argument, found: array", "code" : 51276, "codeName" : "Location51276" } : aggregate failed : _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:18:14 _assertCommandWorked@src/mongo/shell/assert.js:618:17 assert.commandWorked@src/mongo/shell/assert.js:708:16 DB.prototype._runAggregate@src/mongo/shell/db.js:266:5 DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1046:12 @(shell):1:1
In this case, we tried to find the size of an array, but that’s not one of the supported BSON types, so we get an error.
However, we can still get the size of individual array elements (as long as they’re one of the supported types).
Example:
db.posts.aggregate([
{
$project: {
"tagsSize": { $binarySize: { $arrayElemAt: [ "$tags", 0 ] } }
}
}
])
Result:
{ "_id" : 1, "tagsSize" : 4 }
In this example, we get the size of the first array element (arrays are zero based, so 0
refers to the first element).
Document Size
MongoDB also has the $bsonSize
operator, which enables you to get the size of a document.
Another way to get a document’s size is to use the Object.bsonSize()
method.