$indexOfCP (Index of Substring in Code Points)
Last updated: 2026-10-09
$indexOfCP (Index of Substring in Code Points)
$indexOfCP returns the code-point (character) index of the first occurrence of a substring, or -1 when not found. It counts in characters, matching human perception and staying safe with Chinese and emoji — the preferred choice for text work. Optional start and end bound the window, also in code points. It pairs with $substrCP and $strLenCP for slicing. Any null argument yields null.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $indexOfCP: [ <string-expression>, <substring>, <start>, <end> ] }
⚙️ Parameters
| string | Required; the source string. |
|---|---|
| substring | Required; the substring to find. |
| start/end | Optional search window, in code points. |
Returns:The code-point 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):
// $indexOfCP: locate the @ in emails
db.users.aggregate([
{ $project: { at: { $indexOfCP: [ '$email', '@' ] } } }
])
Output:
{ "_id": 1, "at": 6 }
{ "_id": 2, "at": -1 }
📌 Notes
- Zero-based; Chinese characters and emoji each count as 1
- Usually combined with $substrCP and $strLenCP for slicing
- start/end beyond the string length clamp to bounds — no error
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is returned when not found?
A-1.
QDoes it match $indexOfBytes?
ASame for pure ASCII; different with Chinese — $indexOfCP gives character positions.
QWhat about an empty substring?
AIt returns the start index (0 by default), as most languages do.