我有一个类架构如下
const AttendanceSchema = new mongoose.Schema({
date: Date,
records: [{
studentId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
attendance: Boolean
}]
})
var ClassSchema = new mongoose.Schema({
title: String,
description: String,
attendances: [AttendanceSchema]
});
这里我有考勤对象来维持班级学生的出勤率。因此,每天,每当我们从课堂上出勤时,我们都可以 $push 一个带有日期和出勤记录详细信息的对象。一个 Class 对象看起来像这样
{
title: "Class Name",
description: "Description",
attendances: [
{
_id: "60ed395fb06f1254b0771ce1",
date: "2021-07-13T06:57:00.000+00:00",
records: [
{
attendance: true,
_id: "60ed395fb06f1254b0771ce2",
studentId: "60e6c440c133a9b590f510d5"
},
{
attendance: false,
_id: "60ed395fb06f1254b0771ce3",
studentId: "60e6c4cb7be1ce4b647c546f"
}
]
},
{
_id: "60ed395fb06f1254b0771ce4",
date: "2021-07-14T06:57:00.000+00:00"
records: [
{
attendance: true,
_id: "60ed395fb06f1254b0771ce5",
studentId: "60e6c440c133a9b590f510d5"
},
{
attendance: true,
_id: "60ed395fb06f1254b0771ce6",
studentId: "60e6c4cb7be1ce4b647c546f"
}
]
}
]
}
在这里您可以看到每个记录对象都包含一个带有对象 ID 的对象。我想以相同的格式获取学生的详细信息所需的输出
title: "Class Name"
description: "Description"
attendances: [
{
_id: 60ed395fb06f1254b0771ce1
date: 2021-07-13T06:57:00.000+00:00
records: [
{
attendance: true
_id: 60ed395fb06f1254b0771ce2
studentId: 60e6c440c133a9b590f510d5
_studentDetail: {
name: "Name"
detail: ...
}
},
{
attendance: false
_id: 60ed395fb06f1254b0771ce3
studentId: 60e6c4cb7be1ce4b647c546f
}
]
},
...
]
如果我使用 $lookup,我只能在单独的对象中获取学生详细信息。我怎么才能得到它?
由于您的数据结构是深度嵌套的,因此您需要studentIds
在运行$lookup之前提取所有数据结构。在$降低与运营商一起$ addFields可以使用它。
从第二个集合中获取所有学生后,每个文档中都有两个数组:students
和attendances
。然后,您需要通过运行多个$map运算符以及$mergeObjects和$filter来合并它们,以获得每个匹配的学生record
:
db.Attendance.aggregate([
{
$addFields: {
students: {
$reduce: {
input: "$attendances",
initialValue: [],
in: { $setUnion: [ "$$value", "$$this.records.studentId" ] }
}
}
}
},
{
$lookup: {
from: "Students",
localField: "students",
foreignField: "_id",
as: "students"
}
},
{
$project: {
title: 1,
description: 1,
attendances: {
$map: {
input: "$attendances",
as: "a",
in: {
$mergeObjects: [
"$$a",
{
records: {
$map: {
input: "$$a.records",
as: "r",
in: {
attendance: "$$r.attendance",
_id: "$$r._id",
student: {
$arrayElemAt: [
{ $filter: { input: "$students", cond: { $eq: [ "$$this._id", "$$r.studentId" ] } } }
, 0
]
}
}
}
}
}
]
}
}
}
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句