用“$ arrayElemAt”投影返回的元素

如果我在这里混淆了一些术语,请原谅我,但是我正在使用'$ lookup'操作符在聚合中执行连接操作,如下所示:

db.collection('items').aggregate([{$match: {}}, { $lookup: { from: 'usr', localField: 'usr._id', foreignField: '_id', as: '__usr' } }, { $project: { info: 1, timestamp: 1, usr: { "$arrayElemAt": [ "$__usr", 0 ] } } }], (err, result) => { res.json(result); db.close(); }); 

我在聚合结果上执行投影,我使用'$ arrayElemAt'从结果数组中提取单个'usr'匹配。 出于显而易见的原因,我不想返回包含敏感信息的整个“usr”logging。 我正在做的是对使用'$ arrayElemAt'操作返回的元素执行投影。 我能够做到这一点的唯一方法是使用原始投影的额外投影,如下所示:

 db.collection('items').aggregate([{$match: {}}, { $lookup: { from: 'usr', localField: 'usr._id', foreignField: '_id', as: '__usr' } }, { $project: { info: 1, timestamp: 1, usr: { "$arrayElemAt": [ "$__usr", 0 ] } } }, { $project: { info: 1, timestamp: 1, usr: { "username": 1 } } }], (err, result) => { res.json(result); db.close(); }); 

有没有一种方法来实现这个没有重复的投影?

您可以使用$letexpression式将$arrayElemAt返回的值赋给variables,并使用点符号来访问inexpression式中的子文档字段。

 "usr": { "$let": { "vars": { "field": { "$arrayElemAt": [ "$__usr", 0 ] } }, "in": "$$field.username" }