投影返回"$ arrayElemAt"的元素 [英] Project an element returned with "$arrayElemAt"
问题描述
如果我在这里混淆一些术语,请原谅我,但是我正在使用'$ lookup'运算符在聚合中执行联接操作,如下所示:
Forgive me if I confuse some terminology here, but I'm performing a join operation in an aggregation using the '$lookup' operator as shown here:
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"记录. 我要执行的操作是对使用'$ arrayElemAt'操作返回的元素执行投影. 我能够完成此操作的唯一方法是使用原始投影的其他投影,如下所示:
I'm performing a projection on the aggregation result, and I'm using '$arrayElemAt' to extract the single 'usr' match from the resulting array. For obvious reasons, I don't want to return the entire 'usr' record which contains sensitive information. What I'm looking to do is perform a projection on the element returned using the '$arrayElemAt' operation. The only way I've been able to accomplish this is to use an additional projection of the original projection, like so:
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();
});
有没有一种方法可以在没有重复投影的情况下完成此任务?
Is there a way to accomplish this without the duplicated projection?
推荐答案
看来这是 still ,截至2018年8月,这是完成通过$project
管道阶段.虽然@styvane上面的 方法确实可行,并且确实很新颖,但它却增加了管道的复杂性,因此我很犹豫地接受此作为答案.
It looks like this is still, as of August 2018, the best way to accomplish the projection of a document joined via $lookup
to a single embedded document and filter it's fields is still via a secondary $project
pipeline stage. While the method shown by @styvane above does work, and is indeed very novel, it adds even more complexity to the pipeline so I'm hesitant to accept this as the answer.
这篇关于投影返回"$ arrayElemAt"的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!