查询1
(放松)
- 您可以进行嵌套映射和过滤,但这里我们只选择 1 个考试
所以我猜数据很小,为了简单起见,我们可以使用双重展开
- 匹配_id
- 放松
exams
- 匹配
exam_name
- 放松
student_exams
- 匹配
email
- 项目只保留
professor_notes 和mark
- 如果您只想要最多 1 个结果,最后还要添加一个阶段
{"limit" : 1}
Test code here
aggregate(
[{"$match": {"$expr": {"$eq": ["$_id", 1]}}},
{"$unwind": {"path": "$exams"}},
{"$match": {"$expr": {"$eq": ["$exams.exam_name", "exam1"]}}},
{"$unwind": {"path": "$exams.student_exams"}},
{"$match":
{"$expr": {"$eq": ["$exams.student_exams.student_email", "email1"]}}},
{"$project":
{"_id": 0,
"professor_notes": "$exams.student_exams.professor_notes",
"mark": "$exams.student_exams.mark"}}])
查询2
(嵌套地图/过滤器)
- map if not match null else map 再次做同样的事情
- 在返回过滤器上删除空值
- 获取第一个,第一个并替换根
*查询很大,它做同样的事情,映射而不是展开,过滤而不是匹配(2 map/2 unwind,2 filter/2 match)
Test code here
aggregate(
[{"$match": {"$expr": {"$eq": ["$_id", 1]}}},
{"$replaceRoot":
{"newRoot":
{"$arrayElemAt":
[{"$arrayElemAt":
[{"$filter":
{"input":
{"$map":
{"input": "$exams",
"in":
{"$cond":
[{"$not": [{"$eq": ["$$exam.exam_name", "exam1"]}]}, null,
{"$filter":
{"input":
{"$map":
{"input": "$$exam.student_exams",
"in":
{"$cond":
[{"$not":
[{"$eq":
["$$students_exam.student_email", "email1"]}]},
null,
{"professor_notes":
"$$students_exam.professor_notes",
"mark": "$$students_exam.mark"}]},
"as": "students_exam"}},
"cond": {"$ne": ["$$students_exam", null]},
"as": "students_exam"}}]},
"as": "exam"}},
"cond": {"$ne": ["$$exam", null]},
"as": "exam"}}, 0]}, 0]}}}])