$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.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $substrBytes: [ <string-expression>, <byte-start>, <byte-length> ] }
⚙️ Parameters
| string | Required; the source string expression. |
|---|---|
| byte start index | Required integer in bytes, zero-based. |
| byte length | Required 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
- A Chinese character takes 3 UTF-8 bytes; byte cutting can split a character
- Negative start gives an empty string; negative length gives the rest
- Identical results to $substrCP for pure ASCII
🏷️ Related Tags
💡 Related Cases
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.