MongoDB $split Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $split?

$split is a MongoDB aggregation expression that divides a string into an array of substrings using a delimiter. The delimiter is removed. If it is not found, you get a one-element array with the original string.

Remember
$split = String.prototype.split for aggregation

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

"a,b,c" + ","  → ["a", "b", "c"]
"hello" + ","  → ["hello"]   // delimiter not found

null / missing string → null
non-string / empty "" delimiter → pipeline error
UsePrefer
CSV / tags string → array$split
Pick one piece after splitting$split + $arrayElemAt
Join strings into one string$concat
Fixed-position substring$substr / $substrCP

How to Use $split in MongoDB

Pass the string and the delimiter, then optionally pick or count pieces from the result array.

  1. Choose an expression stage ($addFields or $project).
  2. Pass the string expression (field path or literal) as the first argument.
  3. Pass the delimiter (for example "," or "@") as the second argument.
  4. Optionally wrap with $arrayElemAt or $size.
PieceRequired?Role
String expressionYesText to split (must resolve to a string)
DelimiterYesNon-empty separator string (or regex on newer versions)
$arrayElemAtNoTake one segment by index

Pseudocode

Pseudocode
for each document:
    s = evaluate(stringExpression)
    d = evaluate(delimiter)
    if s is null or missing:
        result = null
    else if s is not a string or d is empty / invalid:
        error  // aggregation fails
    else if d not found in s:
        result = [s]
    else:
        result = split(s, d)   // array of pieces
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing string-split expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $split: [ <string>, <delimiter> ] }
Return typeArray of strings
No matchOne-element array with the original string
First piece{ $arrayElemAt: [ { $split: [...] }, 0 ] }
Count pieces{ $size: { $split: [...] } }
Sample check"a,b,c" + "," → ["a", "b", "c"]

Live Preview

Watch $split turn a string into an array. Try common delimiters like comma and @.

Simulates $split (same idea as the mongosh examples below).

Result
string    = "mongodb,database,tutorial"
delimiter = ","

$split → ["mongodb", "database", "tutorial"]

{ tags: ["mongodb", "database", "tutorial"] }

Worked Walkthrough — Comma Tags

One article stores tags as a single CSV string. We want a real array for filtering and display.

Calculation
Document:
  { title: "MongoDB Tips", tagCsv: "mongodb,database,tutorial" }

$split(["$tagCsv", ","])

Find each ",":
  "mongodb" | "database" | "tutorial"

Result:
  ["mongodb", "database", "tutorial"]

Check: three pieces, delimiter gone ✓

MongoDB Examples

We store one article with a CSV tag string and an email. First we split the tags, then we split the email at @. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one article titled MongoDB Tips with a comma-separated tag string and an email address. We save it in a collection named articles.

mongosh
db.articles.insertOne({
  _id: 1,
  title: "MongoDB Tips",
  tagCsv: "mongodb,database,tutorial",
  email: "[email protected]"
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in articles. Run find() to see it:

mongosh
db.articles.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id (row number for this lesson)
tagCsv"mongodb,database,tutorial"Tags stuck in one string (not an array yet)
email"[email protected]"Local part + domain, separated by @
Picture
tagCsv as stored:
  "mongodb,database,tutorial"

After $split with ",":
  ["mongodb", "database", "tutorial"]

email as stored:
  "[email protected]"

After $split with "@":
  ["alice", "example.com"]

How It Works

  1. Insert once. insertOne adds a single article document to articles.
  2. Strings stay as written. tagCsv and email are plain strings until we split them.
  3. find() shows the same shape. What you inserted is what you get back—ready for $split next.

Example 2 — Split Comma-Separated Tags

Goal: turn tagCsv into a real tags array using "," as the delimiter.

mongosh
db.articles.aggregate([
  {
    $addFields: {
      tags: {
        $split: ["$tagCsv", ","]
      }
    }
  }
]);

How It Works

  1. Read the stored string. MongoDB already has tagCsv: "mongodb,database,tutorial" from Example 1.
  2. Choose the delimiter. "," marks where each tag ends.
  3. Build an array. $split returns ["mongodb", "database", "tutorial"] and drops the commas.
  4. Keep all fields. $addFields adds tags next to the original tagCsv.

Example 3 — Split Email at @

Same document, but split the email so you can read the username and domain as separate array elements (then pick one with $arrayElemAt if needed).

mongosh
db.articles.aggregate([
  {
    $addFields: {
      emailParts: {
        $split: ["$email", "@"]
      },
      username: {
        $arrayElemAt: [
          { $split: ["$email", "@"] },
          0
        ]
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using email: "[email protected]" from Example 1.
  2. Split at @. $split yields ["alice", "example.com"].
  3. Pick index 0. $arrayElemAt takes the first piece as username.
  4. Easy check. Local part is alice; domain is index 1.

Edge Cases & Pitfalls

Check these before using $split in production pipelines.

no match

Missing delimiter → one element

If the delimiter is absent, you get [originalString], not an empty array. Plan for that in filters.

null

Null and missing become null

Missing string fields return null. Use $ifNull when you want a default string first.

delimiter

Empty delimiter is invalid

An empty string "" as delimiter fails with an error. You cannot use $split to explode into single characters that way.

spaces

Spaces stay on pieces

Splitting "a, b" on "," yields ["a", " b"]. Trim pieces or use ", " as the delimiter when needed.

Performance Notes

ApproachCostBest for
$split alonePer-document string scanCSV tags, emails, simple paths
$split + $arrayElemAtSplit + O(1) index pickUsername / first tag extraction
Store as array fieldNo runtime splitHot paths that filter tags often

Splitting is cheap for short strings. If you query tags often, consider storing a real array field instead of splitting on every read. Filter early with $match when only some documents need parsing.

Key Takeaways

  • Role: string → array of pieces by delimiter.
  • Syntax: { $split: [ string, delimiter ] }.
  • One piece: wrap with $arrayElemAt.
  • No match: returns [originalString].

One line: $split answers “what pieces do I get when I cut this string at every delimiter?”

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"]. Use it inside aggregation expression stages such as $project and $addFields.
Use { $split: [ <string expression>, <delimiter> ] }. The first argument is the string to split; the second is the delimiter (a string, or a regex pattern on newer MongoDB versions).
MongoDB returns a one-element array containing the original string. For example, splitting "hello" by "," returns ["hello"].
$split breaks one string into an array. $concat joins multiple strings into one string. They are opposite directions for simple delimiter-based work.
If the string expression is null or missing, $split returns null. Non-string values cause the aggregation to fail. Use $ifNull when the field may be missing.
Yes. Wrap $split with $arrayElemAt and index 0 (or another index) to pick one segment.

Next: $sqrt

Compute the square root of a number in an aggregation pipeline.

$sqrt tutorial →

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.

9 people found this page helpful