首页 > 解决方案 > MongoDB - 仅获取已填充文档的数组中的第一项 - 例如 user.populate('posts', 'images.0')

问题描述

假设我正在获取一个带有posts字段的用户。每个post都有一个字段images。我想填充用户的帖子,但只从每个帖子中获取第一张图片。我怎样才能做到这一点?我给出了以下作为不起作用的示例:

db.User.findOne().populate('posts', 'images.0')

标签: databasemongodbmongoosemongodb-querymongoose-populate

解决方案


您可以使用$slice投影运算符来指定要在查询结果中返回的数组中的元素数。

db.User.findOne().populate('posts', { 'images': { '$slice': 1 } })

如果要选择直接字符串而不是字符串数组,请使用$arrayElemAt$first聚合运算符从 MongoDB 4.4 开始,

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

推荐阅读