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" }

Updated on: 30-Mar-2020

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements