Bạn có thể thử,
-
$facetđể tạo 2 mảng,userstên chi tiết người dùng và studentId, thứ hai là tất cả chi tiết người dùng trongallUsers -
$projectlặp lại vòng lặp-
$mapđầu vào dưới dạng mảng allUsers -
$mapnhập với tư cách là sinh viênMảng được giới thiệu -
$mapđầu vào dưới dạng mảng sinh viên -
$reduceđể lấy dữ liệu của học sinh từusersmảng khi điều kiện phù hợp
-
-
$unwindgiải cấu trúc mảng allUsers -
$replaceWiththay thế đối tượng allUsers trong thư mục gốc
db.collection.aggregate([
{
$facet: {
users: [
{
$project: {
studentId: 1,
name: 1
// add fields as you want it will automatically reflect in join
}
}
],
allUsers: []
}
},
{
$project: {
allUsers: {
$map: {
input: "$allUsers",
in: {
$mergeObjects: [
"$$this",
{
studentsReffered: {
$map: {
input: "$$this.studentsReffered",
in: {
$mergeObjects: [
"$$this",
{
students: {
$map: {
input: "$$this.students",
as: "s",
in: {
$reduce: {
input: "$users",
initialValue: { studentId: "$$s.studentId" },
in: {
$cond: [
{ $eq: ["$$this.studentId", "$$s.studentId"] },
"$$this",
"$$value"
]
}
}
}
}
}
}
]
}
}
}
}
]
}
}
}
}
},
{ $unwind: "$allUsers" },
{ $replaceWith: "$allUsers" }
])