下面是我在MongoDB集合中拥有的数据。
{ "_id" : ObjectId("758452161603f94848510101"), "exam_date" : ISODate("2020-01-01T00:00:00Z") "passed" : 1 }
{ "_id" : ObjectId("758452161603f94848510102"), "exam_date" : ISODate("2020-01-22T00:00:00Z") "passed" : 0 }
{ "_id" : ObjectId("758452161603f94848510103"), "exam_date" : ISODate("2020-01-28T00:00:00Z") "passed" : 0 }
{ "_id" : ObjectId("758452161603f94848510204"), "exam_date" : ISODate("2020-02-01T00:00:00Z") "passed" : 1 }
{ "_id" : ObjectId("758452161603f94848510205"), "exam_date" : ISODate("2020-02-02T00:00:00Z") "passed" : 0 }
{ "_id" : ObjectId("758452161603f94848510206"), "exam_date" : ISODate("2020-02-03T00:00:00Z") "passed" : 1 }
{ "_id" : ObjectId("758452161603f94848510207"), "exam_date" : ISODate("2020-02-04T00:00:00Z") "passed" : 1 }
下面是我正在做的汇总,但是预计会有不同的输出。
db.students.aggregate([
{$group: {
_id: {$substr: ['$exam_date', 5, 2]},
totalStudents: {$sum: 1}
}}
]);
实际输出:
{ "_id" : "01", "totalStudents" : 3 }
{ "_id" : "02", "totalStudents" : 4 }
预期输出:
{ "_id" : "01", "totalStudents" : 3, "passed" : 1, "failed" : 2}
{ "_id" : "02", "totalStudents" : 4, "passed" : 3, "failed" : 1}