如何进行MongoDB左联接,在右侧保留没有匹配项的文档



我对此有点陌生,所以如果这真的很琐碎,请原谅我。我正在尝试在MongoDB/NodeJS中进行左外部联接。我想要左表中所有匹配的文档,即使右表中没有匹配的文档。我有一系列问题:

{_id: 'question1', text: 'This is a question.'}
{_id: 'question2', text: 'This is another question.'}

以及一组回复,每个回复都与一个用户和一个问题有关:

{_id: 'response1', QID: 'question1', UID: 'player1', response: 'This is my answer.'}

现在,我想得到一个问题列表和用户对每个问题的回答,包括没有记录回答的问题,所以我想从上面的文档中得到的可能是…

{_id: 'question1', text: 'This is a question.', response: {_id: 'response1', QID: 'question1', UID: 'player1', response: 'This is my answer'}}
{_id: 'question2', text: 'This is another question.', response: []}

有没有一种方法可以在聚合管道中做到这一点?当我使用查找来连接对问题的响应,然后匹配UID时,第二个问题会消失,因为没有与之相关的响应(因此,无法满足UID匹配(。

编辑:我尝试的另一件事是在查找阶段使用let/pipeline:

const month = 11;
const year = 2020;
const UID = 'aaaaaaa';
//Only get responses by UID 'aaaaaaa'
const myResponses = await Question.aggregate([
{ $match: { year, month } },
{
$lookup: {
from: Response.collection.name,
let: { questionID: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [{ $eq: ['$$questionID', '$QID'] }, { $eq: ['$UID', UID] }],
},
},
},
],
as: 'Response',
},
},

这很接近,但由于某种原因,匹配UID似乎不起作用,因为它在每条线索上都会为响应返回一个空数组。去掉最后一个$eq条件,只匹配$$questionID和$QID,就可以得到每个问题的所有答案,正如我所期望的那样,但试图检查常数是否相等是行不通的。

提前感谢!

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/根据文件

执行左外部联接