$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.

CategoryString
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $substrCP: [ <string-expression>, <code-point-start>, <code-point-length> ] }

⚙️ Parameters

stringRequired; the source string expression.
code point start indexRequired integer in code points, zero-based.
code point lengthRequired 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏