$indexOfBytes (Index of Substring in Bytes)
Last updated: 2026-10-09
$indexOfBytes (Index of Substring in Bytes)
$indexOfBytes returns the UTF-8 byte index of the first occurrence of a substring, or -1 when not found. Optional start and end bound the search window. Byte and code-point indexes diverge with multi-byte characters: Chinese occupies several bytes, so a byte index can land mid-character — prefer $indexOfCP for user-visible text. Any null argument yields null.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $indexOfBytes: [ <string-expression>, <substring>, <start>, <end> ] }
⚙️ Parameters
| string | Required; the source string. |
|---|---|
| substring | Required; the substring to find. |
| start/end | Optional search window, in bytes. |
Returns:The byte index (zero-based); -1 when not found; null if any argument is null.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $indexOfBytes: locate ERROR in log messages
db.logs.aggregate([
{ $project: { pos: { $indexOfBytes: [ '$msg', 'ERROR' ] } } }
])
Output:
{ "_id": 1, "pos": 12 }
{ "_id": 2, "pos": -1 }
📌 Notes
- Zero-based; -1 when not found
- Byte indexes differ from character indexes for Chinese — $indexOfCP is more intuitive
- start/end are counted in bytes too
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is returned when the substring is absent?
A-1.
QDo positions drift with Chinese text?
AYes — a Chinese char is 3 bytes; prefer $indexOfCP for Chinese text.
QHow to limit the search range?
APass the 3rd and 4th arguments as start and end.