Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to limit string field by words not characters in Aggregation?

My Documents looks like this:

{
   "_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."
}

I want to limit Paragraph field text to 5 words like this:

{
   "_id" : ObjectId("5e41877df4cebbeaebec5146"),
   "Paragraph" : "My Name is John Smith."
}
{
   "_id" : ObjectId("5e4187d7f4cebbeaebec5147"),
   "Paragraph" : "David Miller is a good"
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option is:

db.collection.aggregate([
  db.collection.aggregate([
  {
    $set: {
      Paragraph: {
        $reduce: {
          input: {
            $slice: [
              {
                $split: [
                  "$Paragraph",
                  " "
                ]
              },
              5
            ]
          },
          initialValue: "",
          in: {
            $concat: [
              "$$value",
              {
                $concat: [
                  "$$this",
                  " "
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $set: {
      Paragraph: {
        $substr: [
          "$Paragraph",
          0,
          {
            $subtract: [
              {
                "$strLenCP": "$Paragraph"
              },
              1
            ]
          }
        ]
      },
      
    }
  }
])

See how it works on the playground example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading