Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to limit the amount of characters returned from a field in a MongoDB query?
For this, use MongoDB $substr. Let us first create a collection with documents −
> dblimitTheNumberOfCharactersDemoinsertOne({"Title":"MongoDB is No SQL database"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cf23013b64a577be5a2bc0e")
}
> dblimitTheNumberOfCharactersDemoinsertOne({"Title":"MySQL is a relational database"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cf2302db64a577be5a2bc0f")
}
Following is the query to display all documents from a collection with the help of find() method −
> dblimitTheNumberOfCharactersDemofind()pretty();
This will produce the following document −
{
"_id" : ObjectId("5cf23013b64a577be5a2bc0e"),
"Title" : "MongoDB is No SQL database"
}
{
"_id" : ObjectId("5cf2302db64a577be5a2bc0f"),
"Title" : "MySQL is a relational database"
}
Following is the query to limit the amount of the characters returned from a field in a MongoDB query −
> dblimitTheNumberOfCharactersDemoaggregate(
[
{
$project:
{
Characters: { $substr: [ "$Title", 0, 20 ] }
}
}
]
);
This will produce the following document −
{ "_id" : ObjectId("5cf23013b64a577be5a2bc0e"), "Characters" : "MongoDB is No SQL da" }
{ "_id" : ObjectId("5cf2302db64a577be5a2bc0f"), "Characters" : "MySQL is a relationa" }Advertisements