0

Is there something like "$slice" in mongodb, that retrieves slice of a text feild, instread of array?

I mean as we can get slice of comments in this way: db.posts.find({}, {comments:{$slice: 5}}) // first 5 comments

get slice of descriptions, in some way like this: db.posts.find({}, {description:{$slice: 100}}) // first 100 chars

thanks

1 Answers1

0

MongoDB's $slice operator only applies to arrays, not text fields. If you want to trim strings you'll have to take care of this in the display code for your application (or possibly save a "trimmed" version of the field for display).

Note that if you are truncating text like a comment or description, the usual practice is to truncate to the nearest whole word (so the logic is a bit more involved than a simple # of characters).

eg: How to Truncate a string in PHP to the word closest to a certain number of characters?.

Community
  • 1
  • 1
Stennie
  • 63,885
  • 14
  • 149
  • 175