Get substring in MongoDB aggregate

To extract substring in MongoDB aggregation pipelines, use the $substr operator within the $project stage. This operator extracts a portion of a string starting from a specified position and length.

Syntax

db.collection.aggregate([
    {
        $project: {
            fieldName: { $substr: ["$sourceField", startIndex, length] }
        }
    }
])

Sample Data

db.demo176.insertMany([
    {"ProductName": "PRODUCT-1"},
    {"ProductName": "PRODUCT-102"},
    {"ProductName": "PRODUCT-105"}
])
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3843a09e4f06af551997ef"),
        ObjectId("5e3843a69e4f06af551997f0"),
        ObjectId("5e3843aa9e4f06af551997f1")
    ]
}

Example: Extract First 7 Characters

Extract the first 7 characters from ProductName field ?

db.demo176.aggregate([
    {
        $project: {
            ProductName: { $substr: ["$ProductName", 0, 7] }
        }
    }
])
{"_id": ObjectId("5e3843a09e4f06af551997ef"), "ProductName": "PRODUCT"}
{"_id": ObjectId("5e3843a69e4f06af551997f0"), "ProductName": "PRODUCT"}
{"_id": ObjectId("5e3843aa9e4f06af551997f1"), "ProductName": "PRODUCT"}

Key Points

  • $substr parameters: [sourceField, startIndex, length]
  • Index starts from 0 (zero-based indexing)
  • Use within $project stage to create new fields or modify existing ones

Conclusion

The $substr operator provides efficient string extraction in MongoDB aggregation pipelines. Specify the source field, starting position, and desired length to extract precise substrings from text data.

Updated on: 2026-03-15T01:39:26+05:30

673 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements