database - Mongoose FindOne - 仅返回符合条件的字段
问题描述
我正在尝试查询我的匹配(游戏)集合,并查找某个用户是否已将数据发送到对象的“reportMessages”数组。
const results = await Match.findOne({ 'users': req.params.userIdOfReportSender, '_id': req.params.matchId, 'reportMessages.sentBy': req.params.userIdOfReportSender }, 'reportMessages' )
但是,上述查询返回以下内容:
{
_id: 5fd382c65d5395e0778f2f8a,
reportMessages: [
{
_id: 5fd610f27ae587189c45b6ca,
content: 'jajatest',
timeStamp: 2020-12-13T13:02:42.102Z,
sentBy: 'XbVvm6g3nsRmPg3P1pBvVl84h6C2'
},
{ sentBy: "'anotheruser123" }
]
}
我怎样才能让它只返回第一个reportMessage,即XbVvm6g3nsRmPg3P1pBvVl84h6C2 发送的那个?
Mongoose findOne 文档(https://mongoosejs.com/docs/api.html#model_Model.findOne)表明您可以提供参数来说明要选择的字段(在他们的情况下为“名称长度”但不显示一种方法仅选择符合特定条件的字段。
这甚至可能吗?尝试用谷歌搜索这个看似简单的问题很长一段时间没有成功
亲切的问候
解决方案
您只能使用此聚合查询获取所需的子文档:
Match.aggregate([
{
$match: { _id: req.params.matchId }
},
{
$project: {
reportMessages: {
$filter: {
input: '$reportMessages',
as: 'msg',
cond: { $eq: ['$$msg.sentBy', req.params.userIdOfReportSender] }
}
}
}
},
{
$project: {
reportMessage: { $arrayElemAt: [ '$reportMessages', 0 ] },
}
},
{ $replaceWith: '$reportMessage' }
]);
请注意,您只需要指定文档_id
即可获得单个结果,因为_id
s 是唯一的。
推荐阅读
- mysql - 尝试转储数据库时出现错误 2 或“拒绝访问”
- python - 如何翻转加载的图像精灵?游戏
- python - 应用程序不会在菜单项中放置与号(wxPython)
- assembly - 简单的 hello world 示例 MASM x 32 程序集导致错误链接 2001
- class - 如何在飞镖中动态创建类实例以分配列表
- python - 如何使用 GStreamer CLI 通过 TCP 或 UDP 将 rtsp 视频源转发到接收器?
- python - 在 sympy 中替换一个矩阵
- c# - 如何使用 csvhelper c# 从 csvfile 中解析特定值
- python - 通过固定浮点类别处理具有混合数据类型的对象列
- angular - 如何防止更改 Angular 表单字段时发生多个事件