$ lookup聚合中的$ project [英] $project in $lookup aggregation
问题描述
所以我有以下文件
{
"_id": "5b7dfee3130dd4ff45288882",
"name": "test",
...
"list": {
"_id": "5b7dfee2130dd4ff45288875",
"name": "test"
...
}
}
鉴于list
是通过lookup
+ unwind
创建的,因此我应该如何投影所有主文档的字段,而仅投影list
的_id
和name
,即
How should I go about projecting all of the main document's fields, while only projecting list
's _id
and name
, given that list
was created through a lookup
+ unwind
i.e.
{
"$match": match
},
{
"$lookup": {
from: "lists",
localField: "list",
foreignField: "_id",
as: "list"
}
},
{
"$unwind": "$list"
},
推荐答案
主要挑战是您要主文档中的所有字段(因为您不了解所有字段)加上2个从列表中.
The main challenge is that you want all fields from the main document (since you do not know all of them) plus only 2 from the list.
这应该做到:
{
$project: {
"_id": 0,
"document": "$$CURRENT",
"list._id": "$$CURRENT.list._id",
"list.name": "$$CURRENT.list.name"
}
}, {
$project: {
"document.list": 0
}
}, {
$addFields: {
"document.list._id": "$$CURRENT.list._id",
"document.list.name": "$$CURRENT.list.name"
}
}, {
$replaceRoot: {
newRoot: "$document"
}
}
它经历了几个阶段,但完成了工作:).它将使用当前文档以及仅所需的列表字段.然后它将从当前文档中删除其列表.然后,它将添加到同一文档列表(因为其中包含我们想要的特定字段).然后它将这些字段添加到文档中,最后将根替换为该文档.
It goes through few stages but gets the job done :). It would take the current document and only the list fields you want. Then it would remove from the current doc its list. Then it would add to that same doc the list (since that one is with the specific fields we want). Then it would add those fields to the document and lastly it would replace the root with that document.
这篇关于$ lookup聚合中的$ project的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!