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

CategoryString
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $indexOfBytes: [ <string-expression>, <substring>, <start>, <end> ] }

⚙️ Parameters

stringRequired; the source string.
substringRequired; the substring to find.
start/endOptional 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

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

🙏 帮我们做得更好

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

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