$substrCP (Substring by Code Points)
Last updated: 2026-10-09
$substrCP (Substring by Code Points)
$substrCP extracts a substring counting positions in Unicode code points (roughly characters). It is fully safe for multi-byte text such as Chinese, Japanese, and emoji, making it the recommended operator for user-visible text. Compared with byte-counting $substrBytes, its semantics match how humans count characters. Negative start yields an empty string; negative length yields the rest.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $substrCP: [ <string-expression>, <code-point-start>, <code-point-length> ] }
⚙️ Parameters
| string | Required; the source string expression. |
|---|---|
| code point start index | Required integer in code points, zero-based. |
| code point length | Required integer in code points. |
Returns:The extracted substring; null if any argument is null.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $substrCP: first 2 characters of nicknames
db.users.aggregate([
{ $project: { nickname: { $substrCP: [ '$name', 0, 2 ] } } }
])
Output:
{ "_id": 1, "nickname": "阿明" }
{ "_id": 2, "nickname": "小美" }
📌 Notes
- Counts code points — one Chinese character or emoji counts as 1
- Negative start gives an empty string; negative length gives the rest
- Pair with $strLenCP to avoid out-of-range cutting
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow many characters is an emoji?
AMost emoji are one code point (counted as 1), but composite emoji may take several.
QWhen to choose $substrCP over $substrBytes?
AUse $substrCP for user-visible text; $substrBytes for exact byte counts.
QWhat if the length exceeds the string?
AIt returns whatever remains — no error.