The $indexOfBytes operator finds where a substring first appears inside a string, measured in bytes. It returns a zero-based byte index or -1 when the text is not found. Use it in aggregation pipelines for URL checks, keyword detection, and text parsing.
01
Substring Search
Find text inside strings.
02
Byte Index
Positions counted in bytes.
03
Syntax
String, search, start, end.
04
$project Stage
Add computed index fields.
05
Use Cases
URLs, keywords, parsing.
06
Not Found
Returns -1 on miss.
Fundamentals
Definition and Usage
In MongoDB’s aggregation framework, the $indexOfBytes operator searches a string for the first occurrence of a substring and returns its zero-based byte index. For example, searching "Hello MongoDB" for "Mongo" returns 6 (the byte position where "Mongo" starts). If the substring is absent, the result is -1.
Byte indexing matters because UTF-8 characters can use more than one byte. For plain ASCII text, byte indexes match character positions. When working with emoji or international text, consider $indexOfCP for code-point-based indexing instead.
💡
Beginner Tip
Think of $indexOfBytes as MongoDB’s version of JavaScript’s string.indexOf(substring), but with byte-based offsets. Use it inside aggregation expression stages like $project and $addFields, not as a query filter operator.
Foundation
📝 Syntax
The $indexOfBytes operator takes a string expression, a substring, and optional byte range bounds:
// "https://codetofun.com/mongodb"
// → pathSlashIndex: 20 (first "/" after "https://")
// Skipping "https://" avoids matching the slashes in the protocol
How It Works
The third argument (start) is a byte offset, not a character index. For https:// URLs, starting at byte 8 skips the protocol and searches only the host and path portion.
Example 3 — Check Whether a Substring Exists
Convert the byte index into a boolean mentionsMongoDB field:
// title contains "MongoDB" → mentionsMongoDB: true
// title without "MongoDB" → mentionsMongoDB: false
How It Works
When the index is -1, $gte returns false. When the substring is found (index 0 or higher), the result is true. This is a common pattern for keyword detection in aggregation pipelines.
Example 4 — $indexOfBytes Inside $cond
Label pages as internal or external based on whether the URL contains your domain:
If $indexOfBytes finds "codetofun.com" in the URL, the index is >= 0 and $cond outputs "internal". Otherwise the link is labeled "external". Pair with $substrBytes when you need to extract text after the found position.
Requiring index >= 1 ensures @ is not the first character. This is a basic sanity check — not full email validation — but it shows how byte indexes power simple text rules in pipelines.
Applications
🚀 Use Cases
Keyword detection — check whether titles, descriptions, or logs contain specific text.
URL and path parsing — locate slashes, domains, or file extensions in URL strings.
Data validation — verify that required symbols (like @ in emails) appear at expected positions.
Conditional labeling — drive $cond logic based on whether a substring is present.
🧠 How $indexOfBytes Works
1
MongoDB reads the string and substring
The pipeline evaluates the source string (e.g. "$title") and the text to find (e.g. "MongoDB").
Input
2
$indexOfBytes scans the byte range
MongoDB walks from start to end byte offsets, comparing substrings until a match is found.
Search
3
The byte index is stored in the pipeline
A zero-based byte index is written to your output field, or -1 if no match exists in the range.
Output
=
📊
Precise substring positions
You get byte index data ready for existence checks, conditional labels, and string slicing with $substrBytes.
Wrap Up
Conclusion
The $indexOfBytes operator is an essential string tool in MongoDB aggregation pipelines. It tells you where a substring first appears, measured in bytes — enabling keyword checks, URL parsing, and conditional text logic without leaving the database.
For beginners, the key idea is simple: wrap your string and substring in { $indexOfBytes: [ ... ] } inside a stage like $project. A result of -1 means “not found”; any index 0 or higher means the substring was located. For international text or emoji, consider $indexOfCP next.
Check for -1 before using the index with $substrBytes
Use $gte: [ { $indexOfBytes: ... }, 0 ] for existence booleans
Pass start to skip known prefixes (e.g. https://)
Use $indexOfBytes for ASCII and byte-level string work
Pair with $cond for link type or category labeling
❌ Don’t
Use $indexOfBytes as a query filter outside expressions
Confuse it with $indexOfArray (arrays vs strings)
Assume byte indexes equal character indexes for all UTF-8 text
Forget that missing substrings return -1, not null
Rely on it alone for full email or URL validation
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $indexOfBytes
Use these points when searching substrings in MongoDB.
5
Core concepts
🔍01
Substring Search
Finds text in strings.
Purpose
📝02
Byte Index
Positions in UTF-8 bytes.
Syntax
🛠03
Pipeline Stages
$project, $addFields, $cond.
Usage
🔗04
URL Parsing
Great for path checks.
Use case
⚠05
Not Found
Returns -1.
Edge case
❓ Frequently Asked Questions
$indexOfBytes returns the zero-based byte index of the first occurrence of a substring inside a string. It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $indexOfBytes: [ <string>, <substring>, <start>, <end> ] }. The start and end arguments are optional byte offsets that limit the search range.
It returns -1 when the substring is not present in the string (within the optional start/end byte range). This matches common indexOf-style behavior.
$indexOfBytes counts positions in bytes (UTF-8 encoding). $indexOfCP counts Unicode code points (characters). For ASCII-only text they behave the same; for emoji or multi-byte characters the indexes can differ.
Yes. start is the byte offset where the search begins (default 0). end is the byte offset before which searching stops (default string byte length). Both are measured in bytes, not characters.