How to limit the amount of characters returned from a field in a MongoDB query?

To limit the amount of characters returned from a field in a MongoDB query, use the $substr operator within an aggregation pipeline. This operator extracts a substring from a string field based on starting position and character count.

Syntax

db.collection.aggregate([
    {
        $project: {
            fieldName: { $substr: ["$originalField", startIndex, numberOfCharacters] }
        }
    }
]);

Create Sample Data

db.limitTheNumberOfCharactersDemo.insertMany([
    {"Title": "MongoDB is No SQL database"},
    {"Title": "MySQL is a relational database"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cf23013b64a577be5a2bc0e"),
        ObjectId("5cf2302db64a577be5a2bc0f")
    ]
}

Display all documents to verify the data ?

db.limitTheNumberOfCharactersDemo.find().pretty();
{
    "_id": ObjectId("5cf23013b64a577be5a2bc0e"),
    "Title": "MongoDB is No SQL database"
}
{
    "_id": ObjectId("5cf2302db64a577be5a2bc0f"),
    "Title": "MySQL is a relational database"
}

Example: Limit to 20 Characters

Limit the Title field to the first 20 characters ?

db.limitTheNumberOfCharactersDemo.aggregate([
    {
        $project: {
            Characters: { $substr: ["$Title", 0, 20] }
        }
    }
]);
{ "_id": ObjectId("5cf23013b64a577be5a2bc0e"), "Characters": "MongoDB is No SQL da" }
{ "_id": ObjectId("5cf2302db64a577be5a2bc0f"), "Characters": "MySQL is a relationa" }

Key Points

  • The $substr operator requires three parameters: field, start index (0-based), and character count.
  • Use $project stage in aggregation pipeline to create new fields with limited characters.
  • The original field remains unchanged; only the projected output is modified.

Conclusion

Use $substr within an aggregation pipeline's $project stage to limit character count from string fields. This creates a new field containing the truncated substring while preserving the original data.

Updated on: 2026-03-15T01:29:32+05:30

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements