聚合与$loockup



我在MongoDB中有两个集合,我想从中生成一个报告。收集数据如下

[
{
_id:"1",
name:"stu 1",
class: "7th"
},
{
_id:"2",
name:"stu 2",
class: "7th"
},
{
_id:"3",
name:"stu 1",
class: "7th"
}
]

[
{
_id:"1",
studentIds:["1","3"],
taskName:"Craft work 1"
},
{
_id:"2",
studentIds:["1"],
taskName:"Craft work 2"
}
]

我想使用聚合管道生成的报告如下所示,我被$ lookup pipeline击中了。有人能帮我一下吗?

学生报告

{
_id:1
name: "stu 1",
class: "7th",
tasks: ["Craft work 1", "Craft work 2"] 
},
{
_id:1
name: "stu 2",
class: "7th",
tasks: []   
},
{
_id:1
name: "stu 3",
class: "7th",
tasks: ["Craft work 1", "Craft work 2"] 
}

我假设活动中的studentIds字段应该是一个数组。好像是打错字了。如果是这样,可以使用

聚合所需的输出:https://mongoplayground.net/p/UBE0oNWLBsR

db.students.aggregate([
{
$lookup: {
"from": "activities",
"localField": "_id",
"foreignField": "studentIds",
"as": "tasks"
}
},
{
$addFields: {
tasks: "$tasks.taskName"
}
}
])

相关内容

  • 没有找到相关文章

最新更新