
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" }
- Related Questions & Answers
- How to limit the amount of characters returned from a field in a MongoDB?
- MongoDB query to limit the returning values of a field?
- How to query MongoDB with a LIMIT?
- How to limit the number of results returned from grep in Linux?
- Limit number of values in a field using MongoDB?
- Limit number of values in a field with MongoDB?
- How to limit the number of characters allowed in form input text field?
- How to trim spaces from field in MongoDB query?
- MongoDB query for a single field
- MongoDB query select and display only a specific field from the document?
- How to give a limit to the input field in HTML?
- MongoDB query to add up the values of a specific field in documents
- How to remove a field completely from a MongoDB document?
- MongoDB query to insert but limit the total records
- MongoDB query to collectively match intersection of documents against a field
Advertisements