$split (Split String)
Last updated: 2026-10-09
$split (Split String)
$split breaks a string into an array of substrings by a delimiter — a staple for CSV-ish text, tag lists, and paths. The delimiter must be a non-empty string; an empty delimiter splits by individual code points. It pairs well with array operators like $arrayElemAt and $size. If either argument is null or missing, the result is null.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $split: [ <string-expression>, <delimiter> ] }
⚙️ Parameters
| string | Required; the string or expression to split. |
|---|---|
| delimiter | Required, non-empty; an empty string splits by code points. |
Returns:An array of substrings; null if either argument is null.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $split: split comma-separated tags into an array
db.products.aggregate([
{ $project: { tags: { $split: [ '$tagStr', ',' ] } } }
])
Output:
{ "_id": 1, "tags": [ "sale", "new", "hot" ] }
{ "_id": 2, "tags": [ "featured" ] }
📌 Notes
- Empty delimiter splits by code points, one element per character
- If the delimiter never occurs, the array holds the original string
- null/missing arguments yield null
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan the delimiter be an empty string?
AYes — an empty string splits by individual code points.
QHow to get the first element after splitting?
AUse $arrayElemAt with index 0.
QWhat if the delimiter never occurs?
AThe array contains only the original string.