Let's say I have a blog with some very long posts.
So, I want to display a list of my posts in "preview mode", for instance only first 50 chars of text.
Simple answer is to do this:
Post.find(
(err, posts) => {
if(err) return console.log(err);
posts.forEach(
post => {
console.log('post preview:', post.data.substr(0,50) + '...');
}
)
}
)
This way we retrieve all data from specific collection. If each post has more than 3 KB of data retrieving 30 posts seems very inefficient in terms of data transfer and processing.
So, I wondered if there is a way to retrieve already sliced string from DB?
Or at least do you have a better solution for my issue?
yes, you can use the $substr operator with a query like this :
db.collection.aggregate(
[
{
$project:
{
preview: { $substr: [ "$data", 0, 50 ] }
}
}
]
)
Edit:
$substr is deprecated from mongodb 3.4 because it only has a well-defined behavior for strings of ASCII characters. If you're facing UTF-8 issues, consider upgrading to mongodb 3.4 in order to use the $substrCP operator so your query becomes :
db.collection.aggregate(
[
{
$project:
{
preview: { $substrCP: [ "$data", 0, 50 ] }
}
}
]
)
As of today, mongodb 3.4 is only available for development, but a production version should be released soon