Home » MongoDB: How to Split String into Array of Substrings

MongoDB: How to Split String into Array of Substrings

by Tutor Aspire

You can use the following syntax to split a string into an array of substrings in MongoDB:

db.myCollection.aggregate([
  { $project: { split_field: { $split: [ "$field1", " " ] } } },
  { $merge: "myCollection" }
])

This particular example splits the string in “field1” based on spaces into a new field titled “split_field” and adds the new field to the collection titled myCollection.

The following example shows how to use this syntax in practice with a collection teams with the following documents:

db.teams.insertOne({name: "Dallas Mavs", points: 31})
db.teams.insertOne({name: "San Antonio Spurs", points: 22})
db.teams.insertOne({name: "Houston Rockets", points: 19})
db.teams.insertOne({name: "Boston Celtics", points: 26})
db.teams.insertOne({name: "Cleveland Cavs", points: 33})

Example: Split String into Array of Substrings in MongoDB

We can use the following code to split the string in the “name” column into an array of strings and display the results in a new field titled “split_name” in the teams collection:

db.teams.aggregate([
  { $project: { split_name: { $split: [ "$name", " " ] } } },
  { $merge: "teams" }
])

Here’s what the updated collection now looks like:

{ _id: ObjectId("62014a924cb04b772fd7a938"),
  name: 'Dallas Mavs',
  points: 31,
  split_name: [ 'Dallas', 'Mavs' ] }
{ _id: ObjectId("62014a924cb04b772fd7a939"),
  name: 'San Antonio Spurs',
  points: 22,
  split_name: [ 'San', 'Antonio', 'Spurs' ] }
{ _id: ObjectId("62014a924cb04b772fd7a93a"),
  name: 'Houston Rockets',
  points: 19,
  split_name: [ 'Houston', 'Rockets' ] }
{ _id: ObjectId("62014a924cb04b772fd7a93b"),
  name: 'Boston Celtics',
  points: 26,
  split_name: [ 'Boston', 'Celtics' ] }
{ _id: ObjectId("62014a924cb04b772fd7a93c"),
  name: 'Cleveland Cavs',
  points: 33,
  split_name: [ 'Cleveland', 'Cavs' ] } 

Notice that every document has a new field titled “split_name” that contains an array of substrings from the “name”  field.

For this particular example we chose to separate the original string using an empty space as a delimiter. 

If the string happens to be separated by a different delimiter (like a dash, slash, colon, etc.) then simply use that delimiter in the $split function instead.

Note: You can find the complete documentation for the $split function here.

Additional Resources

The following tutorials explain how to perform other common operations in MongoDB:

MongoDB: How to Check if Field Contains a String
MongoDB: How to Add a New Field
MongoDB: How to Remove a Field

You may also like