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

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

Problem Description:

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

Solution – 1

One option is to use $split, $slice and $reduce:

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

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject