MongoDB $strLenCP Operator

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

What Is $strLenCP?

$strLenCP is a MongoDB aggregation expression that returns the length of a string in Unicode code points—how many characters the string has. Use it for user-facing limits. For storage bytes, use $strLenBytes.

Remember
$strLenCP = character count (code points) for aggregation

{ $strLenCP: <string expression> }

"hello" → 5
"café"  → 4
"🙂"    → 1   (often 4 bytes in UTF-8)

null / missing → pipeline error
need bytes? → use $strLenBytes
UsePrefer
Character / display limits$strLenCP
Storage / byte budget$strLenBytes
Cut string by characters$substrCP
Legacy byte-based substring$substr / $substrBytes

How to Use $strLenCP in MongoDB

Pass a string field (or literal), then compare the character 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 $strLenCP.
  4. Optionally compare with $strLenBytes when storage also matters.
PieceRequired?Role
$strLenCPYesUnicode code-point 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 = unicodeCodePointCount(s)
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while measuring character length.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $strLenCP: <string> }
CountsUnicode code points (characters)
vs $strLenBytesCharacters vs UTF-8 bytes
Null-safe pattern{ $strLenCP: { $ifNull: ["$title", ""] } }
Empty string$strLenCP("") → 0
Sample check"café" → 4; "🙂" → 1

Live Preview

Watch $strLenCP count characters. Compare ASCII text with accents and emoji.

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

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

{ chars: 5, bytes: 5 }

Worked Walkthrough — café

The word café has 4 characters. Byte length is higher because é needs 2 UTF-8 bytes—but $strLenCP still reports 4.

Calculation
String: "café"

Code points:
  c, a, f, é  → 4 characters

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

Check: user sees 4 letters; storage uses 5 bytes ✓

MongoDB Examples

We store two short titles: plain ASCII and accented text. First we measure characters, then we compare with byte length. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

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

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

How the Data Is Stored in MongoDB

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

mongosh
db.titles.find()

Read those documents like this:

Field in MongoDBValuePlain English
text (doc 1)"hello"5 characters → 5 code points
text (doc 2)"café"4 characters; é is still one code point
Picture
"hello" → h e l l o → 5 code points

"café"  → c a f é   → 4 code points

Form rule example:
  max 10 characters → use $strLenCP, not $strLenBytes

How It Works

  1. Insert once. insertMany adds two title documents to titles.
  2. Strings stay as written. Accents are still single characters even if they use more bytes.
  3. find() shows the same shape. What you inserted is what you get back—ready for $strLenCP next.

Example 2 — Measure Character Length

Goal: add a chars field with the code-point length of each text value.

mongosh
db.titles.aggregate([
  {
    $addFields: {
      chars: { $strLenCP: "$text" }
    }
  }
]);

How It Works

  1. Read each string. MongoDB already has "hello" and "café" from Example 1.
  2. Count code points. $strLenCP counts characters, not UTF-8 bytes.
  3. ASCII is simple. "hello" → 5.
  4. Accents count as one. "café" → 4, even though é uses 2 bytes in storage.

Example 3 — Characters vs Bytes

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

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

How It Works

  1. Same stored titles. Still using hello and café from Example 1.
  2. Characters. $strLenCP reports what users count.
  3. Bytes. $strLenBytes reports UTF-8 storage size.
  4. Easy check. For café, chars = 4 but bytes = 5—pick the operator that matches your rule.

Edge Cases & Pitfalls

Check these before using $strLenCP in production pipelines.

null

Null and missing error

Null/missing input fails the pipeline. Wrap with $ifNull first when fields can be absent.

vs bytes

Not the same as byte length

Emoji and accents make $strLenBytes larger than $strLenCP. Use code points for display limits.

slice

Pair with the matching slice

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

grapheme

Code points ≠ grapheme clusters

Some “single” emoji or accented glyphs are multiple code points combined. $strLenCP counts code points, not visual grapheme clusters.

Performance Notes

ApproachCostBest for
$strLenCP alonePer-document Unicode scanForm limits, display validation
+ $strLenBytesTwo length passesTeaching / dual constraints
$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 character-count check.

Key Takeaways

  • Role: Unicode code-point (character) length.
  • Use when: user-facing character limits matter.
  • Bytes: use $strLenBytes instead.
  • Nulls: error — default with $ifNull first.

One line: $strLenCP answers “how many Unicode characters does this string have?”—not how many UTF-8 bytes it stores.

Frequently Asked Questions

$strLenCP returns the length of a string in Unicode code points—how many characters the string has. For example, { $strLenCP: "hello" } returns 5, and { $strLenCP: "café" } returns 4. Use it inside aggregation expression stages such as $project and $addFields.
Use { $strLenCP: <string expression> }. The argument can be a field like "$title" or a literal string.
$strLenCP counts code points (characters). $strLenBytes counts UTF-8 storage bytes. One emoji is often 1 code point but 4 bytes, so the two values can differ.
Use $strLenCP for user-facing character limits—form fields, display validation, and any rule based on how many characters appear, not how many bytes are stored.
If the argument is null or the field is missing, $strLenCP fails with an error. Guard with $ifNull (for example default to "") before measuring.
Yes for simple Unicode. Spreading a string into code points (or Array.from) matches the idea better than string.length, which counts UTF-16 code units. Run $strLenCP in the aggregation pipeline, not as a standalone find() filter.

Next: $substr

Extract a portion of a string in an aggregation pipeline.

$substr tutorial →

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