【发布时间】:2021-03-01 03:11:29
【问题描述】:
我有两个不同的文档
Accounts
[
{_id:1, name:'xyz'},
{_id:2, name:'abc'},
{_id:3, name:'def'},
{_id:4, name:'pqr'},
]
和
Responses
[
{_id:01, accountId:2, questionId: 0001, res: true},
{_id:02, accountId:2, questionId: 0002, res: true},
{_id:03, accountId:1, questionId: 0003, res: false},
{_id:03, accountId:3, questionId: 0002, res: false},
{_id:03, accountId:2, questionId: 0003, res: false},
]
我如何计算单个帐户的 true 和 false 响应数,同时保留其原始字段。
例如。
{
_id: 2,
name: 'abc',
trueResponses: 2,
falseResponses: 1
}
我尝试使用 $lookup 将另一个文档加入某个字段,但无法计算不同的响应。
db.accounts.aggregate([
{
$match: { _id: 2 }
},
{
$lookup:{
from: 'responses',
localField: '_id',
foreignField: 'accountId',
as: 'responses'
}
}
])
【问题讨论】:
标签: mongodb mongoose aggregation-framework