聚合和 $lookup
Aggregation & $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"
}
]
我想使用聚合管道生成的报告如下所示,我对 $loockup 管道感到震惊。有人可以帮我解决这个问题吗?
学生报告
{
_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"
}
}
])
我在 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"
}
]
我想使用聚合管道生成的报告如下所示,我对 $loockup 管道感到震惊。有人可以帮我解决这个问题吗?
学生报告
{
_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"
}
}
])