-
-
Save ntub46010/0bcd5ab0b49e37cd2e175a5d4ef74d9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
db.student.aggregate( | |
[ | |
{ | |
"$match": { | |
"grade": 4 | |
} | |
}, | |
{ | |
"$unwind": { | |
"path": "$courseIds", | |
"preserveNullAndEmptyArrays": true | |
} | |
}, | |
{ | |
"$lookup": { | |
"localField": "courseIds", | |
"from": "course", | |
"foreignField": "_id", | |
"as": "courseInfo" | |
} | |
}, | |
{ | |
"$unwind": { | |
"path": "$courseInfo", | |
"preserveNullAndEmptyArrays": true | |
} | |
}, | |
{ | |
"$group": { | |
"_id": "$_id", | |
"name": { | |
"$first": "$name" | |
}, | |
"grade": { | |
"$first": "$grade" | |
}, | |
"courseInfoList": { | |
"$push": "$courseInfo" | |
} | |
} | |
}, | |
{ | |
"$addFields": { | |
"totalPoint": { | |
"$sum": "$courseInfoList.point" | |
}, | |
"amountOfCourse": { | |
"$size": "$courseInfoList" | |
} | |
} | |
} | |
] | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"_id": "C1", | |
"name": "程式設計", | |
"point": 5 | |
}, | |
{ | |
"_id": "C2", | |
"name": "英文", | |
"point": 3 | |
}, | |
{ | |
"_id": "C3", | |
"name": "計算機概論", | |
"point": 4 | |
} | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"_id": "S1", | |
"name": "Vincent", | |
"grade": 4, | |
"courseIds": ["C1", "C2"] | |
}, | |
{ | |
"_id": "S2", | |
"name": "Dora", | |
"grade": 3, | |
"courseIds": ["C2", "C3"] | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment