[英]Mongodb: How to group the result of a $lookup and map them to a list objects that contain a matching key?
我有包含“模塊”的課堂文檔,整個文檔如下所示:
{
"_id": "628a7ea21e2a666d7872efbf",
"name": "Test Class",
"owner": "60763491b98b9e186ef33137",
"schoolId": "607dff27c712219af1e65d83",
"description": "This is a test class.",
"roster": [],
"modules": [
{
"name": "Test Module 1",
"id": "62a7082d0bf84c43fdfe95ff",
"isPublished": false
},
{
"name": "Test Module 2",
"id": "62a72d6378ce044dca32e1a2",
"isPublished": false
}
]
}
我也有這樣的任務文件:
{
"classroomId": "628a7ea21e2a666d7872efbf",
"moduleId": "62a7082d0bf84c43fdfe95ff",
"name": "Assignment 1",
"description": "Test description",
"created": 1655120822055,
"reading": null,
"questions": [],
"isPublished": true,
"_id": "62a723b6683ffc4b11940c7b"
}
我的問題是如何進行聚合,以便如果我想查找課堂作業,我可以按 moduleId 對作業文檔進行分組,然后將它們作為一個字段添加到模塊數組中。 最終文件是這樣的:
{
"_id": "628a7ea21e2a666d7872efbf",
"name": "Test Class",
"owner": "60763491b98b9e186ef33137",
"schoolId": "607dff27c712219af1e65d83",
"description": "This is a test class.",
"roster": [],
"modules": [
{
"name": "Test Module 1",
"id": "62a7082d0bf84c43fdfe95ff",
"isPublished": false,
"assignments": [
{
"_id": "62a708ab0bf84c43fdfe9600",
"classroomId": "628a7ea21e2a666d7872efbf",
"moduleId": "62a7082d0bf84c43fdfe95ff",
"name": "Assignment 1",
"description": "Test description",
"created": 1655113899629,
"due": null,
"settings": null,
"reading": null,
"questions": [],
"isPublished": true
},
{
"_id": "62a723b6683ffc4b11940c7b",
"classroomId": "628a7ea21e2a666d7872efbf",
"moduleId": "62a7082d0bf84c43fdfe95ff",
"name": "Assignment 1",
"description": "Test description",
"created": 1655120822055,
"due": null,
"settings": null,
"reading": null,
"questions": [],
"isPublished": true
}
]
},
{
"name": "Test Module 2",
"id": "62a72d6378ce044dca32e1a2",
"isPublished": false,
"assignments": [
]
}
]
}
現在我只有基本查找,顯然這只是讓我得到一個單獨的分配字段,沒有組。
lookup = [
{
$lookup: {
from: "assignments",
localField: "modules.id",
foreignField: "moduleId",
as: "assignments"
}
}
];
$lookup
$set
- 設置modules
字段。
2.1. $map
- 迭代modules
數組並返回一個新數組。
2.1.1. $mergeObject
- 將當前迭代module
文檔與結果2.1.1.1中帶有assignments
數組的文檔合並。
2.1.1.1。 $filter
- 通過匹配moduleId
過濾assignments
數組。
$unset
- 刪除assignments
字段。
db.classroom.aggregate([
{
$lookup: {
from: "assignments",
localField: "modules.id",
foreignField: "moduleId",
as: "assignments"
}
},
{
$set: {
modules: {
$map: {
input: "$modules",
as: "module",
in: {
$mergeObjects: [
"$$module",
{
"assignments": {
$filter: {
input: "$assignments",
as: "asgn",
cond: {
$eq: [
"$$module.id",
"$$asgn.moduleId"
]
}
}
}
}
]
}
}
}
}
},
{
$unset: "assignments"
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.