MongoDB $strLenBytes Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
String Operations

What You’ll Learn

The $strLenBytes operator returns how many bytes a string occupies in UTF-8 encoding. Use it for storage validation, index size checks, and any scenario where byte length matters more than visible character count.

01

Byte Length

UTF-8 storage size.

02

Syntax

One string expression.

03

ASCII vs UTF-8

1 byte per ASCII char.

04

$project Stage

Add length fields.

05

Use Cases

Limits, validation.

06

vs $strLenCP

Bytes vs code points.

Definition and Usage

In MongoDB’s aggregation framework, the $strLenBytes operator counts the number of bytes in a string. MongoDB stores strings as BSON UTF-8, so plain ASCII characters use one byte each, while accented letters, CJK characters, and emoji may use two, three, or four bytes per character.

For example, { $strLenBytes: "hello" } returns 5. A string with emoji can have fewer visible characters but more bytes. When you need character count instead, use $strLenCP (code points).

💡
Beginner Tip

For English-only ASCII text, byte length equals character count. As soon as your data includes international text or emoji, byte length and character count can differ.

📝 Syntax

The $strLenBytes operator takes one string expression:

mongosh
{ $strLenBytes: <string expression> }

Literal Examples

mongosh
{ $strLenBytes: "hello" }
// Result: 5  (5 ASCII bytes)

{ $strLenBytes: "café" }
// Result: 5  (é uses 2 bytes in UTF-8)

{ $strLenBytes: "$message" }
// Byte length of the message field

Syntax Rules

  • $strLenBytes — returns an integer byte count.
  • <string expression> — field path, literal, or nested string expression.
  • Use inside $project, $addFields, $set, or $match with $expr.
  • ASCII characters — typically 1 byte each.
  • Multi-byte UTF-8 characters — 2–4 bytes each.
  • null input — returns null.

💡 $strLenBytes vs $strLenCP

$strLenBytes — counts bytes (storage size in UTF-8)
$strLenCP — counts Unicode code points (visible characters)
Example: "Hi 👋" — ~7 bytes, ~4 code points
Use bytes for storage limits; use code points for user-facing length limits.

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (string)
Syntax{ $strLenBytes: <string> }
OutputInteger (byte count) or null
EncodingUTF-8 (BSON default)
Related operator$strLenCP for character count
Common stages$project, $addFields, $match + $expr
ASCII
{
  $strLenBytes: "hello"
}

Returns 5

Field
{
  $strLenBytes: "$text"
}

Field byte length

Filter
$gt: [
  { $strLenBytes: "$msg" },
  280
]

Over limit

Null
{
  $strLenBytes: null
}

Returns null

Examples Gallery

Measure byte length on ASCII and UTF-8 strings, filter by size limits, and compare with character-based length.

📚 Basic Byte Length

Start with a messages collection and compute byte length with $project.

Sample Input Documents

Suppose you have a messages collection with text fields of varying length:

mongosh
[
  { "_id": 1, "text": "Hello" },
  { "_id": 2, "text": "MongoDB rocks!" },
  { "_id": 3, "text": "café" },
  { "_id": 4, "text": "Hi 👋" }
]

Example 1 — Basic $strLenBytes on a Field

Add a byteLength field to each document:

mongosh
db.messages.aggregate([
  {
    $project: {
      text: 1,
      byteLength: { $strLenBytes: "$text" }
    }
  }
])

How It Works

Each character’s UTF-8 encoding determines the byte count. ASCII letters use one byte; extended characters and emoji use more.

📈 Validation and Comparison

Filter by byte limits and compare byte length with code-point length.

Example 2 — Bytes vs Code Points

Compare $strLenBytes with $strLenCP on the same string:

mongosh
db.messages.aggregate([
  {
    $project: {
      text: 1,
      bytes:    { $strLenBytes: "$text" },
      codePoints: { $strLenCP: "$text" }
    }
  }
])

// "Hi 👋"  → bytes: 7,  codePoints: 4
// "Hello"  → bytes: 5,  codePoints: 5

How It Works

When bytes exceed code points, the string contains multi-byte UTF-8 characters. This is normal for international text and emoji.

Example 3 — Filter Messages Over a Byte Limit

Find messages longer than 280 bytes (useful for storage or API limits):

mongosh
db.messages.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          { $strLenBytes: "$text" },
          280
        ]
      }
    }
  },
  {
    $project: {
      text: 1,
      byteLength: { $strLenBytes: "$text" }
    }
  }
])

How It Works

Wrap $strLenBytes in a comparison inside $expr. Only documents exceeding the byte threshold pass the $match stage.

Example 4 — Validation Flag with $addFields

Add a boolean field indicating whether text fits within a byte budget:

mongosh
db.messages.aggregate([
  {
    $addFields: {
      byteLength: { $strLenBytes: "$text" },
      withinLimit: {
        $lte: [
          { $strLenBytes: "$text" },
          100
        ]
      }
    }
  }
])

// text under 100 bytes → withinLimit: true
// text over 100 bytes  → withinLimit: false

How It Works

Combine $strLenBytes with $lte or $gte to build validation flags without changing the original text field.

Bonus — Empty String and Null

Edge cases for missing or empty values:

mongosh
db.messages.aggregate([
  {
    $project: {
      emptyLen: { $strLenBytes: "" },
      nullLen:  { $strLenBytes: null },
      safeLen:  {
        $strLenBytes: {
          $ifNull: [ "$text", "" ]
        }
      }
    }
  }
])

// ""   → 0
// null → null
// $ifNull guards missing fields

How It Works

An empty string has zero bytes. Use $ifNull when the field may be missing so you get 0 instead of null.

🚀 Use Cases

  • Storage validation — enforce maximum byte size before writing to MongoDB or an external API.
  • Index key sizing — check whether a string field approaches index key byte limits.
  • International content — measure UTF-8 footprint for multilingual apps.
  • Data quality reports — flag unusually long fields for cleanup or truncation.

🧠 How $strLenBytes Works

1

MongoDB reads the string

The expression resolves to a BSON UTF-8 string from a field path or literal.

Input
2

UTF-8 bytes are counted

Each character’s encoded bytes are summed. ASCII = 1 byte; extended Unicode may use more.

Count
3

An integer is returned

The total byte count is stored in the field you define in the pipeline stage.

Output
=

Byte length known

Use for limits, validation, and comparison with $strLenCP.

Conclusion

The $strLenBytes operator measures string length in UTF-8 bytes inside aggregation pipelines. It is essential when storage size, index limits, or byte-based API constraints matter more than visible character count.

For user-facing character limits, pair your knowledge with $strLenCP. Next in the series: $strLenCP.

💡 Best Practices

✅ Do

  • Use $strLenBytes for storage and index byte-limit checks
  • Compare with $strLenCP when debugging UTF-8 length differences
  • Guard null fields with $ifNull: [ "$field", "" ]
  • Combine with $gt, $lte in $expr for filtering
  • Test with emoji and accented characters, not just ASCII

❌ Don’t

  • Use byte length for user-facing “character count” UI — prefer $strLenCP
  • Assume 1 character always equals 1 byte
  • Confuse $strLenBytes with JavaScript’s .length (UTF-16 code units)
  • Forget that null input returns null
  • Truncate strings by byte count without proper UTF-8 handling (use $substrBytes instead)

Key Takeaways

Knowledge Unlocked

Five things to remember about $strLenBytes

Use these points when measuring strings in MongoDB.

5
Core concepts
📝 02

{ $strLenBytes: s }

One argument.

Syntax
🌐 03

Multi-byte UTF-8

Emoji & accents.

Encoding
🛠 04

Size limits

Filter & validate.

Use case
05

vs $strLenCP

Bytes vs chars.

Compare

❓ Frequently Asked Questions

$strLenBytes returns the length of a string measured in bytes, not characters. For plain ASCII text like "hello", the byte length is 5. For UTF-8 strings with accents or emoji, multi-byte characters count as multiple bytes.
The syntax is { $strLenBytes: <string expression> }. The expression can be a field reference like "$message" or a literal string.
$strLenBytes counts bytes (storage size in UTF-8). $strLenCP counts Unicode code points (visible characters). For example, one emoji may be 1 code point but 4 bytes.
Use $strLenBytes when you care about storage limits, index key size, or wire-protocol byte constraints. Use $strLenCP when you care about how many characters the user sees.
If the string expression is null or missing, $strLenBytes returns null. Use $ifNull to provide a default empty string when needed.

Continue the Operator Series

Move on to $strLenCP for code-point character counts, or review $strcasecmp for case-insensitive comparison.

Next: $strLenCP →

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.

5 people found this page helpful