Tutorialspoint

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


1 Answer
Arjun Thakur

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.