The $substr operator extracts part of a string starting at a zero-based index for a given length. Use it to pull prefixes, suffixes, IDs, and fixed-width segments from text fields in aggregation pipelines.
01
Substring
Slice any string.
02
Syntax
[ str, start, len ].
03
Zero-Based
Start at index 0.
04
$project Stage
New sliced fields.
05
Use Cases
Codes, masking, trim.
06
vs $substrCP
Legacy vs Unicode.
Fundamentals
Definition and Usage
In MongoDB’s aggregation framework, the $substr operator returns a substring of a string. You specify where to start (zero-based index) and how many characters to include. For example, { $substr: [ "hello world", 0, 5 ] } returns "hello".
This is similar to JavaScript’s String.substring() or String.slice(). MongoDB also offers $substrBytes (byte positions) and $substrCP (code-point positions) for more precise Unicode handling.
💡
Beginner Tip
Index 0 is the first character. To skip the first three characters, use start 3. For international text and emoji, prefer $substrCP over $substr.
Foundation
📝 Syntax
The $substr operator takes a string, start index, and length:
Increase the start index to skip a known prefix. Adjust length to capture the segment you need, or use a large length to grab the rest (MongoDB stops at the string end).
Example 4 — Mask a Phone Number
Show only the last four digits by combining $strLenCP and $substr:
The space at index 5 is skipped when you start the second slice at index 6. This mirrors how zero-based indexing works in most programming languages.
Applications
🚀 Use Cases
Fixed-width parsing — extract category codes, region prefixes, or legacy ID segments.
Display truncation — show a short preview of long text fields in reports.
Data masking — hide all but the last few digits of phone numbers or account IDs.
Normalization — strip known prefixes before matching or grouping.
🧠 How $substr Works
1
MongoDB reads the string
The first argument resolves to a string from a field path or literal.
Input
2
Start index is applied
MongoDB moves to the zero-based start position. If start is past the end, the result is empty.
Position
3
Length characters are taken
The operator returns up to length characters from that position.
Extract
=
✂
Substring returned
Use in $project, combine with $concat, or chain with other string ops.
Wrap Up
Conclusion
The $substr operator extracts part of a string using a zero-based start index and a length. It is a foundational tool for parsing fixed-width text, truncating display values, and masking sensitive data in aggregation pipelines.
For Unicode-heavy content, prefer $substrCP or $substrBytes. Next in the series: $substrBytes.
Use $substr for ASCII fixed-width parsing and simple slices
Prefer $substrCP when emoji or international text is involved
Combine with $strLenCP to slice from the end (masking)
Guard null fields with $ifNull before slicing
Test edge cases: empty strings, start beyond length, length longer than remainder
❌ Don’t
Assume one index unit equals one visible character for all Unicode text
Confuse $substr with $slice (arrays vs strings)
Use negative start indices — $substr requires non-negative start
Forget that out-of-range start returns an empty string, not an error
Hard-code byte positions for UTF-8 text — use $substrCP instead
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $substr
Use these points when slicing strings in MongoDB.
5
Core concepts
✂01
Substring
Slice strings.
Purpose
📝02
[ s, start, len ]
Three arguments.
Syntax
🔢03
Index 0
Zero-based start.
Rule
🛠04
Masking
Last N digits.
Pattern
⚠05
vs $substrCP
Unicode-safe.
Compare
❓ Frequently Asked Questions
$substr returns part of a string starting at a zero-based index for a given length. For example, { $substr: [ "hello world", 0, 5 ] } returns "hello". It is used inside aggregation stages like $project and $addFields.
The syntax is { $substr: [ <string>, <start>, <length> ] }. Start is the zero-based index where extraction begins; length is how many characters to include.
$substr is a legacy alias. MongoDB recommends $substrBytes (byte-based positions) or $substrCP (code-point positions) for Unicode-safe substring extraction. $substr behaves like $substrBytes in current versions.
$substr returns an empty string when the start index is greater than or equal to the string length.
If the string expression is null, $substr returns null. Use $ifNull to provide a default empty string when the field may be missing.