我有一个包含以下值的文档的集合
{
"_id": ObjectID("XXXXXX"),
"more details" :more details
"attendance": [
{
"date": ISODate("2015-08-11T18:30:00.000Z"),
"students": [
{
"studentId": ObjectID("YYYYYY"),
"entryTime": ISODate("1970-01-01T05:41:00.000Z"),
"exitTime": ISODate("1970-01-01T05:41:00.000Z"),
"attendanceStatus": "Present"
},
{
"studentId": ObjectID("ZZZZZZ"),
"entryTime": ISODate("1970-01-01T06:42:00.000Z"),
"exitTime": ISODate("1970-01-01T06:42:00.000Z"),
"attendanceStatus": "Present"
}
]
},
{
"date": ISODate("2015-08-12T18:30:00.000Z"),
"students": [
{
"studentId": ObjectID("XXXXX"),
"entryTime": ISODate("1970-01-01T05:41:00.000Z"),
"exitTime": ISODate("1970-01-01T06:42:00.000Z"),
"attendanceStatus": "Present"
},
{
"studentId": ObjectID("YYYYY"),
"entryTime": ISODate("1970-01-01T05:41:00.000Z"),
"exitTime": ISODate("1970-01-01T06:42:00.000Z"),
"attendanceStatus": "Absent"
}
]
}
]
}
我想知道学生在场的天数以及他缺席的天数。但我不断得到输出未定义。
var pipeline = [
{
"$match": {_id: mongoose.Types.ObjectId(batchId)}
},
{
"$project": {attendance: '$attendance.students'}
},
{
"$group": {
"studentId": "$studentId"
,
"Present": {
"$sum": {
"$cond": [{"$eq": ["attendanceStatus", "Present"]}, 1, 0]
}
},
"Absent": {
"$sum": {
"$cond": [{"$eq": ["attendanceStatus", "Absent"]}, 1, 0]
}
}
}
}
];
无法弄清楚我错过了什么
答案 0 :(得分:0)
请尝试此管道
var pipeline = [{$unwind: '$attendance'},
{$unwind: '$attendance.students'},
{$group: {
_id: '$attendance.students.studentId',
"Present": {
"$sum": {
"$cond": [
{"$eq": ["$attendance.students.attendanceStatus", "Present"]},
1,
0]
}
},
"Absent": {
"$sum": {
"$cond": [
{"$eq": ["$attendance.students.attendanceStatus", "Absent"]},
1,
0]
}
}}}]