Skip to content

Instantly share code, notes, and snippets.

@ntub46010
Created March 24, 2022 15:17
Show Gist options
  • Save ntub46010/0bcd5ab0b49e37cd2e175a5d4ef74d9e to your computer and use it in GitHub Desktop.
Save ntub46010/0bcd5ab0b49e37cd2e175a5d4ef74d9e to your computer and use it in GitHub Desktop.
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"
}
}
}
]
);
[
{
"_id": "C1",
"name": "程式設計",
"point": 5
},
{
"_id": "C2",
"name": "英文",
"point": 3
},
{
"_id": "C3",
"name": "計算機概論",
"point": 4
}
]
[
{
"_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