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
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
$substroperator requires three parameters: field, start index (0-based), and character count. - Use
$projectstage 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.
Advertisements
