Introduction to MongoDB $binarySize Operator

$binarySize is a MongoDB aggregation operator that is used to get the number of bytes of binary data fields. It can be used in queries and aggregation pipeline operations.

Syntax

The syntax of the $binarySize operator is as follows:

{ $binarySize: <expression> }

Where <expression> represents the binary data field to get the number of bytes from.

Use Cases

The $binarySize operator can be used in queries and aggregation pipeline operations to help filter or calculate the number of bytes of binary data fields.

For example, in a query, we can use $binarySize to query binary data fields with a specific number of bytes:

db.collection.find({ binField: { $binarySize: 4 } })

In an aggregation pipeline operation, we can use $binarySize to calculate the number of bytes of binary data fields and perform aggregation:

db.collection.aggregate([
  { $project: { binField: 1, binSize: { $binarySize: "$binField" } } },
  { $group: { _id: "$binSize", count: { $sum: 1 } } }
])

Examples

Suppose we have a users collection containing user IDs and avatar data. We can use the $binarySize operator to get the number of bytes of the avatar data.

Insert some test data:

db.users.insertMany([
  {
    userId: 1,
    avatar: BinData(
      0,
      "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mN8z8AARgEGBHg5/gAAAABJRU5ErkJggg=="
    )
  },
  {
    userId: 2,
    avatar: BinData(
      0,
      "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mN8z8AARgEGBHg5/gAAAABJRU5ErkJggg=="
    )
  },
  {
    userId: 3,
    avatar: BinData(
      0,
      "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mN8z8AARgEGBHg5/gAAAABJRU5ErkJggg=="
    )
  }
])

Query users with avatar data size of 21 bytes:

db.users.find({ avatar: { $binarySize: 21 } })

Count the number of users with each avatar data size:

db.users.aggregate([
  { $project: { userId: 1, avatarSize: { $binarySize: "$avatar" } } },
  { $group: { _id: "$avatarSize", count: { $sum: 1 } } }
])

The above code will query users with avatar data size of 21 bytes and count the number of users with each avatar data size.

Conclusion

The $binarySize operator is a MongoDB aggregation operator that is used to get the number of bytes of binary data fields. It can be used in queries and aggregation pipeline operations.