Say I'm fetching a user with a posts
field. Each post
has a field images
. I want to populate the posts on the user, but only fetch the first image from each post. How can I do this? I've given the following as an example that does not work:
db.User.findOne().populate('posts', 'images.0')
You can use $slice projection operator to specifies the number of elements in an array to return in the query result.
db.User.findOne().populate('posts', { 'images': { '$slice': 1 } })
If you want to select direct string instead of array of string use $arrayElemAt or $first aggregation operator Starting from MongoDB 4.4,
$arrayElemAt
db.User.findOne().populate('posts', { 'images': { '$arrayElemAt': ["$images", 0] } })
$first
db.User.findOne().populate('posts', { 'images': { '$first': "$images" } })