Database MongoDB-仅获取已填充文档上数组中的第一项-例如user.populate('posts','images.0'))

Database MongoDB-仅获取已填充文档上数组中的第一项-例如user.populate('posts','images.0')),database,mongodb,mongoose,mongodb-query,mongoose-populate,Database,Mongodb,Mongoose,Mongodb Query,Mongoose Populate,假设我正在获取一个带有posts字段的用户。每个帖子都有一个字段图像。我想在用户上填充帖子,但只从每篇帖子中获取第一张图片。我该怎么做?我举了以下不起作用的例子: db.User.findOne().populate('posts', 'images.0') 可以使用投影运算符指定数组中要在查询结果中返回的元素数 db.User.findOne().populate('posts', { 'images': { '$slice': 1 } }) 如果要从MongoDB 4.4开始选择直接字符

假设我正在获取一个带有posts字段的用户。每个帖子都有一个字段图像。我想在用户上填充帖子,但只从每篇帖子中获取第一张图片。我该怎么做?我举了以下不起作用的例子:

db.User.findOne().populate('posts', 'images.0')
可以使用投影运算符指定数组中要在查询结果中返回的元素数

db.User.findOne().populate('posts', { 'images': { '$slice': 1 } })
如果要从MongoDB 4.4开始选择直接字符串而不是字符串数组使用或聚合运算符

$arrayElemAt 美元优先
db.User.findOne().populate('posts', { 'images': { '$arrayElemAt': ["$images", 0] } })
db.User.findOne().populate('posts', { 'images': { '$first': "$images" } })