MongoDb聚合,用于根据相同集合的所有文档中数组对象中存在的ID过滤列表 [英] MongoDb aggregation for filtering list based on ids present in object of array from all document of same collection
问题描述
在我的mongodb中,我的数据如下所示:
In my mongodb I have the data as shown below:
{
"studentId": "a1",
"name":"John Doe"
"studentsReffered": [
{
"course": "BTECH",
"students": [
{
"studentId": "a2"
},
{
"studentId": "a3"
}
]
},
{
"course": "MTECH",
"students": [
{
"studentId": "a4"
},
{
"studentId": "a5"
}
]
}
]
},
{
"studentId": "a2",
"name":"Joseph"
"studentsReffered": [
{
"course": "BTECH",
"students": [
{
"studentId": "a6"
}
]
}
]
}
以上JSON包含MongoDB集合中的文档.每个文档都包含学生的所有详细信息以及推荐详细信息摘要.即,对于每个学生,都有一个fieldsReferred字段,其中包含该学生推荐的所有学生的ID.
Above JSON contains documents in collection of MongoDB. Each document contains all details of student along with referral detail summary. i.e. for every student there is a field studentsReferred which contain ids of all students which are referred by the student.
我想单独显示所有学生的详细信息,以及在检索单个学生时被推荐的学生的姓名.如下
I want to show all details of student alone with the name of students which are reffered while retrieving the single student. As below
{
"studentId": "a1",
"name":"John Doe"
"studentsReffered": [
{
"course": "BTECH",
"students": [
{
"studentId": "a2",
"name":"Joseph"
},
{
"studentId": "a3",
"name":"Lorem Ipsum"
}
]
},
{
"course": "MTECH",
"students": [
{
"studentId": "a4",
"name":"Lorem Ipsum"
},
{
"studentId": "a5",
"name":"Lorem Ipsum"
}
]
}
]
}
我尝试使用mongodb聚合解决此问题.但不幸的是,我无法为此编写查询.因此,我们可以使用聚合来实现上述方案.
I have tried to use mongodb aggregation for this problem. But unfortunately I am not able write query for that. So can we achieve the above scenario using aggregation.
推荐答案
您可以尝试
-
$ facet
创建2个数组,users
用户详细信息名称和studentId,第二个所有用户详细信息在allUsers
中 -
$ project
迭代循环-
$ map
输入为allUsers数组 -
$ map
输入为studentsReffered数组 -
$ map
输入为学生数组 -
$ reduce
在条件匹配时从users
数组中获取学生的数据
$facet
to create 2 arrays,users
user details name and studentId, second all users details inallUsers
$project
iterate loop$map
input as allUsers array$map
input as studentsReffered array$map
input as students array$reduce
to get data of the student fromusers
array when condition match
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" } ])
这篇关于MongoDb聚合,用于根据相同集合的所有文档中数组对象中存在的ID过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-