我有一个学生成绩系统,使用了MongoDB。我在MongoDB中有以下文档:
如何获取一门特定课程
中获得"A"、"B"、"C"、"D"等分数的学生数量。每门课程的"_id"都保持不变。
{
_id: "60b223541338467beaf3ae0d",
studentName: "John Doe"
studentGradingDetails: [
{
_id: "60b21e47e5462929cab27a98",
term: "semester-1",
subject: "chemistry",
grade: "A",
createdAt: "2021-05-29T10:58:15.113Z",
},
{
_id: "60b21e47e5462929cab27a99",
term: "semester-2",
subject: "computer_science",
grade: "B",
createdAt: "2021-05-29T10:58:15.113Z",
},
],
createdAt: "2021-05-29T11:19:48.770Z",
}
{
_id: "60b223541338467beaf3ae0e",
studentName: "Will Smith"
studentGradingDetails: [
{
_id: "60b21e47e5462929cab27a98",
term: "semester-1",
subject: "chemistry",
grade: "D",
createdAt: "2021-05-29T10:58:15.113Z",
},
{
_id: "60b21e47e5462929cab27a99",
term: "semester-2",
subject: "computer_science",
grade: "A",
createdAt: "2021-05-29T10:58:15.113Z",
},
],
createdAt: "2021-05-29T11:19:48.770Z",
}
这是我尝试过的,但卡住了,不确定下一步该怎么做!?
await db.collection("studentsemestergrades")
.aggregate([
{ $unwind: "$studentGradingDetails" },
{
$group: {
_id: "$studentGradingDetails._id",
},
},
])
.toArray();
期望输出:
各科目分数分布情况 (_id)
{
"_id" : "60b21e47e5462929cab27a98",
"A" : 12,
"B" : 20,
"C" : 8,
"D" : 2
},
{
"_id" : "60b21e47e5462929cab27a99",
"A" : 5,
"B" : 2,
"C" : 8,
"D" : 12
}