$substrBytes (Substring by Bytes)

Last updated: 2026-10-09

$substrBytes (Substring by Bytes)

$substrBytes extracts a substring by UTF-8 byte positions; both start and length count bytes. It suits pure-ASCII text (where bytes equal characters) or cases needing exact byte control. Beware: with multi-byte characters like Chinese, a byte boundary can land mid-character and garble output — switch to code-point-based $substrCP then. Negative start yields an empty string; negative length yields the rest.

CategoryString
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $substrBytes: [ <string-expression>, <byte-start>, <byte-length> ] }

⚙️ Parameters

stringRequired; the source string expression.
byte start indexRequired integer in bytes, zero-based.
byte lengthRequired integer in bytes.

Returns:The extracted substring; null if any argument is null.

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $substrBytes: first 10 bytes of content
 db.files.aggregate([
  { $project: { head: { $substrBytes: [ '$content', 0, 10 ] } } }
])

Output:

{ "_id": 1, "head": "hello wor" }
{ "_id": 2, "head": "MongoDB su" }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QCan byte-based cutting garble Chinese?
APossibly — a Chinese char is 3 bytes, and a bad boundary garbles it; prefer $substrCP.
QWhen do results match $substrCP?
AWhen the string is pure ASCII.
QWhat is it good for?
APure-ASCII text or exact byte budgeting.
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%

🙏 帮我们做得更好

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

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