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 $split operator is the modern approach for string splitting in aggregation pipelines.
  • Use $arrayElemAt with index -1 to 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.

Updated on: 2026-03-15T02:06:47+05:30

443 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements