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

Time:12-06

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

CodePudding user response:

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

  • Related