database - MongoDB - 仅获取已填充文档的数组中的第一项 - 例如 user.populate('posts', 'images.0')
问题描述
假设我正在获取一个带有posts
字段的用户。每个post
都有一个字段images
。我想填充用户的帖子,但只从每个帖子中获取第一张图片。我怎样才能做到这一点?我给出了以下作为不起作用的示例:
db.User.findOne().populate('posts', 'images.0')
解决方案
您可以使用$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" } })
推荐阅读
- rsync - 如果更改的文件过多,则停止 rsync 备份
- c# - 我正在寻找一个正则表达式来将响应与 & 作为值的一部分
- java - Selenium + IntelliJ:烦人的警告,如何解决它们
- python - 方法对象在神经网络代码中不可下标
- powershell - 如何通过 azure devops 发布管道中的 powershell 任务创建 azure 资源?
- r - 选择具有最高值的行并返回行名
- javascript - 我对 ${name} 的东西有疑问,我该如何构造它?
- xpath - 如何在 xpath 表达式中添加新行?
- coq - Coq 的归纳谓词的归纳规则中的抽象模式
- azure-functions - 适用于长时间运行活动的 Azure 耐用功能