Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Split a string during MongoDB aggregate
To split a string during MongoDB aggregation, use the $split operator which divides a string into an array based on a delimiter. For more complex operations, you can combine it with other aggregation operators like $project and $arrayElemAt.
Syntax
{ $split: ["$fieldName", "delimiter"] }
Sample Data
db.splitString.insertOne({
"StudentName": "John Smith"
});
{
"acknowledged": true,
"insertedId": ObjectId("5e0849d925ddae1f53b62206")
}
Method 1: Using $split in Aggregation Pipeline
Split the StudentName field and extract the last name using the aggregation framework ?
db.splitString.aggregate([
{
$project: {
StudentName: 1,
NameParts: { $split: ["$StudentName", " "] },
LastName: {
$arrayElemAt: [
{ $split: ["$StudentName", " "] },
-1
]
}
}
}
]);
{
"_id": ObjectId("5e0849d925ddae1f53b62206"),
"StudentName": "John Smith",
"NameParts": ["John", "Smith"],
"LastName": "Smith"
}
Method 2: Using MapReduce (Legacy Approach)
The traditional mapReduce approach for string splitting ?
db.splitString.mapReduce(
function() {
var StudentLastName = this.StudentName.split(/\s/).reverse()[0].toUpperCase();
emit({ "StudentLastName": StudentLastName, "FirstObjectId": this._id }, this);
},
function(){},
{ "out": { "inline": 1 } }
);
{
"results": [
{
"_id": {
"StudentLastName": "SMITH",
"FirstObjectId": ObjectId("5e0849d925ddae1f53b62206")
},
"value": {
"_id": ObjectId("5e0849d925ddae1f53b62206"),
"StudentName": "John Smith"
}
}
],
"ok": 1
}
Key Points
- The
$splitoperator is the modern approach for string splitting in aggregation pipelines. - Use
$arrayElemAtwith index-1to get the last element from the split array. - MapReduce is deprecated; prefer aggregation pipeline for better performance.
Conclusion
Use $split in aggregation pipelines for efficient string splitting in modern MongoDB. The aggregation framework provides better performance and readability compared to the legacy mapReduce approach.
Advertisements
