MongoDB $strLenCP Operator

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

What You’ll Learn

The $strLenCP operator returns how many Unicode code points (visible characters) a string contains. Use it for user-facing character limits, form validation, and display rules where emoji and international text count as one character each.

01

Code Points

Visible char count.

02

Syntax

One string expression.

03

Emoji Friendly

1 emoji = 1 char.

04

$project Stage

Add length fields.

05

Use Cases

Limits, validation.

06

vs $strLenBytes

Chars vs bytes.

Definition and Usage

In MongoDB’s aggregation framework, the $strLenCP operator counts the number of Unicode code points in a string. A code point is roughly what a user sees as one character on screen. For example, { $strLenCP: "hello" } returns 5, and { $strLenCP: "Hi 👋" } returns 4 (H, i, space, wave emoji).

This differs from $strLenBytes, which counts UTF-8 storage bytes. When you enforce a “280 character” post limit or a “50 character” title rule, $strLenCP is the right choice.

💡
Beginner Tip

Think of $strLenCP as counting characters for display purposes. One emoji usually counts as one character, even though it may use multiple bytes in storage.

📝 Syntax

The $strLenCP operator takes one string expression:

mongosh
{ $strLenCP: <string expression> }

Literal Examples

mongosh
{ $strLenCP: "hello" }
// Result: 5

{ $strLenCP: "Hi 👋" }
// Result: 4  (emoji = 1 code point)

{ $strLenCP: "$title" }
// Code-point length of the title field

Syntax Rules

  • $strLenCP — returns an integer code-point count.
  • <string expression> — field path, literal, or nested string expression.
  • Use inside $project, $addFields, $set, or $match with $expr.
  • CP stands for code points (Unicode character units).
  • Empty string — returns 0.
  • null input — returns null.

💡 $strLenCP vs $strLenBytes

$strLenCP — counts code points (what users see): "Hi 👋"4
$strLenBytes — counts UTF-8 bytes (storage): "Hi 👋"7
Use $strLenCP for character limits; use $strLenBytes for storage size.

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (string)
Syntax{ $strLenCP: <string> }
OutputInteger (code-point count) or null
CP meaningUnicode code points (visible characters)
Related operator$strLenBytes for byte count
Common stages$project, $addFields, $match + $expr
ASCII
{
  $strLenCP: "hello"
}

Returns 5

Field
{
  $strLenCP: "$title"
}

Field char count

Limit
$gt: [
  { $strLenCP: "$body" },
  280
]

Over 280 chars

Empty
{
  $strLenCP: ""
}

Returns 0

Examples Gallery

Count visible characters on ASCII and emoji strings, enforce character limits, and compare with byte-based length.

📚 Basic Character Count

Start with a posts collection and compute code-point length with $project.

Sample Input Documents

Suppose you have a posts collection with titles and body text:

mongosh
[
  { "_id": 1, "title": "Hello World", "body": "Short post." },
  { "_id": 2, "title": "MongoDB 🚀", "body": "Learning aggregation today!" },
  { "_id": 3, "title": "café", "body": "Unicode text with accents." },
  { "_id": 4, "title": "Hi 👋", "body": "Wave emoji in title." }
]

Example 1 — Basic $strLenCP on a Field

Add a titleLength field showing how many characters each title has:

mongosh
db.posts.aggregate([
  {
    $project: {
      title: 1,
      titleLength: { $strLenCP: "$title" }
    }
  }
])

How It Works

Each visible character — including emoji and accented letters — counts as one code point. Spaces count too.

📈 Limits and Comparison

Enforce character limits and compare code points with byte length.

Example 2 — Code Points vs Bytes

See how emoji affects byte count but not character count:

mongosh
db.posts.aggregate([
  {
    $project: {
      title: 1,
      chars:  { $strLenCP: "$title" },
      bytes:  { $strLenBytes: "$title" }
    }
  }
])

// "Hi 👋"       → chars: 4,  bytes: 7
// "Hello World" → chars: 11, bytes: 11

How It Works

ASCII-only strings often have equal char and byte counts. Emoji and some Unicode characters use more bytes than code points.

Example 3 — Filter Posts Over 280 Characters

Find posts whose body exceeds a common social-media character limit:

mongosh
db.posts.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          { $strLenCP: "$body" },
          280
        ]
      }
    }
  },
  {
    $project: {
      title: 1,
      charCount: { $strLenCP: "$body" }
    }
  }
])

How It Works

Use $strLenCP inside $expr when the limit is based on visible characters, not storage bytes.

Example 4 — Title Length Validation Flag

Mark titles that exceed 50 characters:

mongosh
db.posts.aggregate([
  {
    $addFields: {
      titleLength: { $strLenCP: "$title" },
      titleTooLong: {
        $gt: [
          { $strLenCP: "$title" },
          50
        ]
      }
    }
  }
])

// title under 50 chars → titleTooLong: false
// title over 50 chars  → titleTooLong: true

How It Works

Combine $strLenCP with comparison operators to build validation flags for forms, admin dashboards, or data cleanup jobs.

Bonus — Characters Remaining

Show how many characters are left before hitting a limit:

mongosh
db.posts.aggregate([
  {
    $project: {
      title: 1,
      charsUsed: { $strLenCP: "$body" },
      charsRemaining: {
        $subtract: [
          280,
          { $strLenCP: "$body" }
        ]
      }
    }
  }
])

How It Works

Subtract the current length from your max limit. Negative values mean the text is over the limit — useful for UI counters like “42 characters remaining.”

🚀 Use Cases

  • User-facing character limits — enforce max title, bio, or post length the way users count characters.
  • Form validation — flag documents where input exceeds allowed character counts.
  • Content moderation — find unusually long fields for review or truncation.
  • Analytics — report average post length in characters for dashboards.

🧠 How $strLenCP Works

1

MongoDB reads the string

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

Input
2

Unicode code points are counted

Each visible character — ASCII, accented letters, emoji — counts as one code point in most cases.

Count
3

An integer is returned

The code-point count is stored in the field you define in the pipeline stage.

Output
=

Character count known

Use for display limits, validation, and comparison with $strLenBytes.

Conclusion

The $strLenCP operator counts string length in Unicode code points — the character count users expect. It is the right tool for display limits, form validation, and content rules that include emoji and international text.

When storage size matters instead, use $strLenBytes. Next in the series: $substr.

💡 Best Practices

✅ Do

  • Use $strLenCP for user-facing character limits
  • Compare with $strLenBytes when debugging UTF-8 differences
  • Guard null fields with $ifNull: [ "$field", "" ]
  • Combine with $subtract to show characters remaining
  • Test with emoji and accented characters, not just ASCII

❌ Don’t

  • Use code-point count for storage or index byte limits — prefer $strLenBytes
  • Assume it matches JavaScript .length for all Unicode (surrogate pairs differ)
  • Confuse $strLenCP with $size (arrays vs strings)
  • Forget that null input returns null
  • Truncate strings by code-point count without $substrCP (use the CP-aware substring operator)

Key Takeaways

Knowledge Unlocked

Five things to remember about $strLenCP

Use these points when counting characters in MongoDB.

5
Core concepts
📝 02

{ $strLenCP: s }

One argument.

Syntax
😀 03

Emoji = 1

Usually 1 char.

Unicode
🛠 04

Char limits

280, 50, etc.

Use case
05

vs $strLenBytes

Chars vs bytes.

Compare

❓ Frequently Asked Questions

$strLenCP returns the length of a string measured in Unicode code points — essentially the number of characters the user sees. For example, { $strLenCP: "hello" } returns 5, and { $strLenCP: "Hi 👋" } returns 4.
The syntax is { $strLenCP: <string expression> }. The expression can be a field reference like "$title" or a literal string.
$strLenCP counts code points (visible 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 — tweet length, form field max characters, display validation, and any rule based on how many characters appear on screen.
If the string expression is null or missing, $strLenCP returns null. Use $ifNull to default to an empty string when you want a count of 0 instead.

Continue the Operator Series

Move on to $substr for extracting substrings, or review $strLenBytes for byte-based length.

Next: $substr →

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