MongoDB $split Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
String Operations

What You’ll Learn

The $split operator breaks a string into an array of substrings using a delimiter. Use it to parse comma-separated tags, email addresses, file paths, and other structured text stored as a single field.

01

String → Array

Split by delimiter.

02

Syntax

[ string, delimiter ].

03

Parse CSV-like

Comma, space, @.

04

$project Stage

New array fields.

05

Use Cases

Tags, emails, paths.

06

vs $concat

Split vs join.

Definition and Usage

In MongoDB’s aggregation framework, the $split operator divides a string wherever a delimiter appears and returns an array of substrings. For example, { $split: [ "a,b,c", "," ] } returns ["a", "b", "c"].

This is the opposite of $concat, which joins strings together. After splitting, you can use $arrayElemAt, $size, or $sortArray on the resulting array.

💡
Beginner Tip

If the delimiter is not found, MongoDB returns an array with the whole string as one element. Empty trailing segments are preserved: "a,b," split on "," gives ["a", "b", ""].

📝 Syntax

The $split operator takes a string and a delimiter:

mongosh
{ $split: [ <string expression>, <delimiter> ] }

Literal Examples

mongosh
{ $split: [ "a,b,c", "," ] }
// Result: ["a", "b", "c"]

{ $split: [ "user@example.com", "@" ] }
// Result: ["user", "example.com"]

{ $split: [ "hello", "," ] }
// Result: ["hello"]  (delimiter not found)

Syntax Rules

  • First argument — string expression (field path or literal).
  • Second argument — delimiter string (field path or literal).
  • Return value — array of substring elements.
  • Delimiter not found — returns [ entire string ].
  • Use inside $project, $addFields, or $set.
  • If the string is null, the result is null.

💡 $split vs $concat

$split — one string + delimiter → array of parts
$concat — multiple strings → one combined string
$split: ["a,b", ","]["a", "b"]
$concat: ["a", ",", "b"]"a,b"

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (string)
Syntax{ $split: [ string, delimiter ] }
OutputArray of strings
No delimiter match[ original string ]
Common stages$project, $addFields, $set
Comma split
{
  $split: ["$csv", ","]
}

CSV-like values

Email @
{
  $split: ["$email", "@"]
}

Local + domain

Path /
{
  $split: ["$path", "/"]
}

Path segments

First part
$arrayElemAt: [...]

After split

Examples Gallery

Parse comma-separated tags, split email addresses, break file paths into segments, and extract the first part with $split.

📚 Comma-Separated Values

Turn a single CSV-style string field into a proper array of tags.

Sample Input Documents

Suppose you have an articles collection with string fields to parse:

mongosh
[
  {
    "_id": 1,
    "title": "MongoDB Tips",
    "tagCsv": "mongodb,database,tutorial",
    "email": "alice@example.com"
  },
  {
    "_id": 2,
    "title": "Node Guide",
    "tagCsv": "nodejs,javascript",
    "email": "bob@company.org"
  },
  {
    "_id": 3,
    "title": "No Tags",
    "tagCsv": "draft",
    "email": "carol@test.io"
  }
]

Example 1 — Split Comma-Separated Tags

Convert a CSV string into an array:

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      tags: {
        $split: [ "$tagCsv", "," ]
      }
    }
  }
])

How It Works

MongoDB splits at every comma. A string with no comma returns a one-element array.

📈 Email, Paths, and Extraction

Parse structured strings and pull out individual parts.

Example 2 — Split Email at @

Separate the local part from the domain:

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      emailParts: {
        $split: [ "$email", "@" ]
      }
    }
  }
])

// alice@example.com → ["alice", "example.com"]
// bob@company.org   → ["bob", "company.org"]

How It Works

Use $arrayElemAt on the result to get index 0 (username) or 1 (domain) separately.

Example 3 — Split a File Path

Break a path string into folder segments:

mongosh
db.files.aggregate([
  {
    $project: {
      name: 1,
      pathSegments: {
        $split: [ "$filepath", "/" ]
      }
    }
  }
])

// "/docs/reports/2024.pdf"
// → ["", "docs", "reports", "2024.pdf"]

How It Works

Leading slashes produce an empty first segment. Filter empty strings afterward if needed.

Example 4 — Extract First Tag After Split

Combine $split with $arrayElemAt to get one value:

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      primaryTag: {
        $arrayElemAt: [
          { $split: [ "$tagCsv", "," ] },
          0
        ]
      }
    }
  }
])

// tagCsv: "mongodb,database,tutorial"
// primaryTag: "mongodb"

How It Works

Split first, then pick an index. This pattern is useful when only the first segment matters for grouping or display.

Bonus — Count Tags After Split

Chain with $size to count how many tags were parsed:

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      tagCount: {
        $size: {
          $split: [ "$tagCsv", "," ]
        }
      }
    }
  }
])

How It Works

$split produces an array; $size counts its elements. Useful for validation and reporting.

🚀 Use Cases

  • CSV import cleanup — convert legacy comma-separated fields into arrays for querying.
  • Email parsing — extract username or domain from an address string.
  • Path and URL parsing — split file paths or URL segments for analysis.
  • Tokenization — break delimited text before sorting, filtering, or set operations.

🧠 How $split Works

1

MongoDB reads the string

The first argument resolves to a string (field path, literal, or nested expression).

Input
2

The delimiter is applied

MongoDB finds every occurrence of the delimiter and cuts the string at those positions.

Split
3

Substrings become an array

Each piece between delimiters becomes an array element. Empty segments are kept.

Output
=

String array

Use with $arrayElemAt, $size, or $sortArray.

Conclusion

The $split operator converts delimited strings into arrays inside aggregation pipelines. It is essential for parsing legacy CSV fields, email addresses, and paths before further array processing.

Chain it with $arrayElemAt to pick one part, or $size to count segments. Next in the series: $sqrt.

💡 Best Practices

✅ Do

  • Use $split to normalize CSV-like string fields into arrays
  • Combine with $arrayElemAt when you need a single segment
  • Use $trim on segments if values may have extra whitespace
  • Guard null strings with $ifNull: [ "$field", "" ]
  • Count parsed items with $size for validation

❌ Don’t

  • Confuse $split (string → array) with $concat (strings → string)
  • Expect regex splitting — $split uses literal delimiter strings only
  • Forget that no delimiter match returns a one-element array
  • Assume trimmed values — spaces around commas stay in the result
  • Use empty string as delimiter — it causes an error

Key Takeaways

Knowledge Unlocked

Five things to remember about $split

Use these points when parsing strings in MongoDB pipelines.

5
Core concepts
📝 02

[ str, delim ]

Two arguments.

Syntax
🛠 03

No match

One-element array.

Rule
🗃 04

+ $arrayElemAt

Pick one part.

Chaining
05

vs $concat

Split vs join.

Compare

❓ Frequently Asked Questions

$split divides a string into an array of substrings using a delimiter. For example, { $split: [ "a,b,c", "," ] } returns ["a", "b", "c"]. It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $split: [ <string expression>, <delimiter> ] }. The first argument is the string to split; the second is the delimiter string. Both can be field references or literals.
MongoDB returns an array containing the entire original string as a single element. For example, $split on "hello" with delimiter "," returns ["hello"].
$split breaks one string into an array using a delimiter. $concat joins multiple strings into one string. They are inverse operations for simple delimiter-based parsing.
If the string expression is null, $split returns null. Use $ifNull to provide a default empty string when the field may be missing.

Continue the Operator Series

Move on to $sqrt for square root calculations, or review $concat for joining strings.

Next: $sqrt →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful