- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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?
To limit the amount of characters returned from a field, use $substr in MongoDB. Let us create a collection with documents −
> db.demo233.insertOne({"Paragraph":"My Name is John Smith.I am learning MongoDB database"}); { "acknowledged" : true, "insertedId" : ObjectId("5e41877df4cebbeaebec5146") } > db.demo233.insertOne({"Paragraph":"David Miller is a good student and learning Spring and Hibernate Framework."}); { "acknowledged" : true, "insertedId" : ObjectId("5e4187d7f4cebbeaebec5147") }
Display all documents from a collection with the help of find() method −
> db.demo233.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e41877df4cebbeaebec5146"), "Paragraph" : "My Name is John Smith.I am learning MongoDB database" } { "_id" : ObjectId("5e4187d7f4cebbeaebec5147"), "Paragraph" : "David Miller is a good student and learning Spring and Hibernate Framework." }
Following is the query to limit the amount of characters returned from a field in MongoDB −
> db.demo233.aggregate( ... [ ... { ... $project: ... { ... Paragraph: { $substr: [ "$Paragraph", 0, 10] } ... ... } ...} ] )
This will produce the following output −
{ "_id" : ObjectId("5e41877df4cebbeaebec5146"), "Paragraph" : "My Name is" } { "_id" : ObjectId("5e4187d7f4cebbeaebec5147"), "Paragraph" : "David Mill" }
Advertisements