MongoDB $strLenBytes Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $strLenBytes?

$strLenBytes is a MongoDB aggregation expression that returns the UTF-8 byte length of a string. ASCII letters are 1 byte each. Accents and emoji often need more bytes than the number of characters you see.

Remember
$strLenBytes = UTF-8 byte count for aggregation

{ $strLenBytes: <string expression> }

"hello" → 5 bytes (ASCII)
"café"  → 5 bytes (é uses 2)
"🙂"    → 4 bytes (1 emoji)

null / missing → pipeline error
need characters? → use $strLenCP
UsePrefer
Storage / byte budget$strLenBytes
Visible character count$strLenCP
Cut string by bytes$substrBytes
Size of any BSON value$binarySize

How to Use $strLenBytes in MongoDB

Pass a string field (or literal), then compare the byte count to a limit if needed.

  1. Choose an expression stage ($addFields or $project).
  2. Ensure the argument is a string (use $ifNull if the field may be missing).
  3. Pass that expression to $strLenBytes.
  4. Optionally compare with $strLenCP to see bytes vs characters.
PieceRequired?Role
$strLenBytesYesUTF-8 byte length
String expressionYesField path or literal string
$ifNullNoDefault to "" so missing fields do not error

Pseudocode

Pseudocode
for each document:
    s = evaluate(stringExpression)
    if s is null or missing:
        error  // aggregation fails
    else if s is not a string:
        error
    else:
        result = utf8ByteLength(s)
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while measuring string byte length.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $strLenBytes: <string> }
CountsUTF-8 bytes (1–4 per character)
vs $strLenCPBytes vs Unicode code points
Null-safe pattern{ $strLenBytes: { $ifNull: ["$msg", ""] } }
Empty string$strLenBytes("") → 0
Sample check"café" → 5 bytes; code points → 4

Live Preview

Watch $strLenBytes count UTF-8 bytes. Compare ASCII text with accents and emoji.

Simulates $strLenBytes (and shows $strLenCP for comparison).

Result
string = "hello"
$strLenBytes → 5
$strLenCP    → 5

{ bytes: 5, chars: 5 }

Worked Walkthrough — café

The word café looks like 4 letters, but UTF-8 stores é with 2 bytes.

Calculation
String: "café"

UTF-8 bytes:
  c → 1
  a → 1
  f → 1
  é → 2
  --------
  total = 5

$strLenBytes("café") → 5
$strLenCP("café")    → 4

Check: characters 4, storage bytes 5 ✓

MongoDB Examples

We store two short messages: plain ASCII and accented text. First we measure bytes, then we compare bytes with code points. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine two messages: hello (ASCII) and café (accented). We save them in a collection named messages.

mongosh
db.messages.insertMany([
  { _id: 1, text: "hello" },
  { _id: 2, text: "café" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in messages. Run find() to see them:

mongosh
db.messages.find()

Read those documents like this:

Field in MongoDBValuePlain English
text (doc 1)"hello"5 ASCII letters → 5 bytes
text (doc 2)"café"4 letters, but é needs 2 UTF-8 bytes
Picture
"hello"
  h a e l l o
  1 1 1 1 1   → 5 bytes

"café"
  c a f é
  1 1 1 2     → 5 bytes

Same byte length, different character count for "café".

How It Works

  1. Insert once. insertMany adds two message documents to messages.
  2. Strings stay as written. MongoDB stores UTF-8 text; accents may use extra bytes.
  3. find() shows the same shape. What you inserted is what you get back—ready for $strLenBytes next.

Example 2 — Measure Byte Length

Goal: add a bytes field with the UTF-8 size of each text value.

mongosh
db.messages.aggregate([
  {
    $addFields: {
      bytes: { $strLenBytes: "$text" }
    }
  }
]);

How It Works

  1. Read each string. MongoDB already has "hello" and "café" from Example 1.
  2. Count UTF-8 bytes. $strLenBytes walks the encoded bytes, not “letters on screen.”
  3. ASCII is simple. "hello" → 5 bytes (one per letter).
  4. Accents cost more. "café" is also 5 bytes because é uses 2.

Example 3 — Bytes vs Code Points

Same data, but also compute $strLenCP so you can see when byte length and character count diverge.

mongosh
db.messages.aggregate([
  {
    $addFields: {
      bytes: { $strLenBytes: "$text" },
      chars: { $strLenCP: "$text" }
    }
  }
]);

How It Works

  1. Same stored messages. Still using hello and café from Example 1.
  2. Bytes. $strLenBytes reports storage size in UTF-8.
  3. Characters. $strLenCP counts Unicode code points.
  4. Easy check. For café, chars = 4 but bytes = 5—that gap is the accent.

Edge Cases & Pitfalls

Check these before using $strLenBytes in production pipelines.

null

Null and missing error

Unlike many math operators, null/missing input fails the pipeline. Wrap with $ifNull first when fields can be absent.

vs CP

Not the same as character count

Emoji and accents make $strLenBytes larger than $strLenCP. Pick based on storage vs display needs.

slice

Pair with the matching slice

Byte limits → $substrBytes. Character limits → $substrCP.

ASCII

ASCII looks identical

For plain English A–Z text, bytes and code points match. The difference appears with international text.

Performance Notes

ApproachCostBest for
$strLenBytes alonePer-document UTF-8 scanShort fields, byte budgets
+ $strLenCPTwo length passesTeaching / validating UTF-8 gaps
$match then lengthFewer docs to measureOnly some rows need a check

Length checks are cheap for short strings. Filter early with $match when only some documents need a byte-size check.

Key Takeaways

  • Role: UTF-8 byte length of a string.
  • Use when: storage, indexes, or payload size matter.
  • Characters: use $strLenCP instead.
  • Nulls: error — default with $ifNull first.

One line: $strLenBytes answers “how many UTF-8 bytes does this string use?”—not how many letters you see.

Frequently Asked Questions

$strLenBytes returns how many UTF-8 bytes a string uses. ASCII letters count as 1 byte each. Accents and emoji often use 2–4 bytes per character. Use it inside aggregation expression stages such as $project and $addFields.
Use { $strLenBytes: <string expression> }. The argument can be a field like "$message" or a literal string.
$strLenBytes counts bytes (storage size in UTF-8). $strLenCP counts Unicode code points (character count). One emoji may be 1 code point but 4 bytes.
Use $strLenBytes for storage limits, index key size, or payload byte budgets. Use $strLenCP when you care about how many characters a user sees.
If the argument is null or the field is missing, $strLenBytes fails with an error. Guard with $ifNull (for example default to "") before measuring.
Yes for UTF-8 strings. Think of $strLenBytes as MongoDB’s aggregation version of counting UTF-8 bytes—run it in the pipeline, not as a standalone find() filter.

Next: $strLenCP

Count Unicode code points when you need character length, not bytes.

$strLenCP tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful