In MongoDB, the $split
aggregation pipeline operator divides a string into an array of substrings based on a delimiter.
The delimiter is removed from the string, and the substrings are added as elements to the array.
To use $split
, you specify the string and the delimiter.
If the delimiter isn’t found in the string, the original string is returned as the only item in the array.
Example 1
Suppose we have a collection called test
with the following document:
{ "_id" : 1, "data" : "March-18-2020" }
We can use $split
to split the data
field at the hyphen.
db.test.aggregate(
[
{ $match: { _id: 1 } },
{
$project:
{
_id: 0,
result: { $split: [ "$data", "-" ] }
}
}
]
)
Result:
{ "result" : [ "March", "18", "2020" ] }
Example 2
Suppose we have the following document:
{ "_id" : 2, "data" : "Sydney, Australia, NSW 2000" }
We can use $split
to separate the data field based on the comma and space:
db.test.aggregate(
[
{ $match: { _id: 2 } },
{
$project:
{
_id: 0,
result: { $split: [ "$data", ", " ] }
}
}
]
)
Result:
{ "result" : [ "Sydney", "Australia", "NSW 2000" ] }
Example 3
Here’s one more example. This time we’re going to split the string based on the space in between each word.
Sample document:
{ "_id" : 3, "data" : "Homer Jay Einstein" }
Let’s split it up:
db.test.aggregate(
[
{ $match: { _id: 3 } },
{
$project:
{
_id: 0,
result: { $split: [ "$data", " " ] }
}
}
]
)
Result:
{ "result" : [ "Homer", "Jay", "Einstein" ] }
Wrong Data Type
The two arguments must be strings. Providing the wrong data type results in an error.
Example:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{
$project:
{
_id: 0,
result: { $split: [ "$data", 18 ] }
}
}
]
)
Result:
Error: command failed: { "ok" : 0, "errmsg" : "$split requires an expression that evaluates to a string as a second argument, found: double", "code" : 40086, "codeName" : "Location40086" } : aggregate failed : _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:18:14 _assertCommandWorked@src/mongo/shell/assert.js:639:17 assert.commandWorked@src/mongo/shell/assert.js:729:16 DB.prototype._runAggregate@src/mongo/shell/db.js:266:5 DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1058:12 @(shell):1:1
As the error message states, $split requires an expression that evaluates to a string as a second argument, found: double
.