英文:
MongoDB - Project data based on array of objects
问题
我有两位家长的学生数据:
{
_id: ObjectId('643f8a6773a92fb1552e4c89'),
studentName: 'Peter Jackson',
studentId: 'SID1001',
grade: 2,
gender: 'Male',
parentDetails: [
{
_id: ObjectId('63fee5a42f60946679146768'),
name: 'Jackson Steve',
email: 'jack.steve@gmail.com',
mobile: 'xxxxxxxxxx',
relation: 'Father'
},
{
_id: ObjectId('6447c1ba22670472ed4b29cc'),
name: 'Amenda Jackson',
email: 'amenda.jack@gmail.com',
mobile: 'xxxxxxxxxx',
relation: 'Mother'
}
]
}
我需要根据每个家长显示学生数据,如下所示:
[
{
studentId: 'SID1001',
studentName: 'Peter Jackson',
grade: 2,
parentName: 'Jackson Steve',
parentEmail: 'jack.steve@gmail.com',
relation: 'Father'
},
{
studentId: 'SID1001',
studentName: 'Peter Jackson',
grade: 2,
parentName: 'Amenda Jackson',
parentEmail: 'amenda.jack@gmail.com',
relation: 'Mother'
}
]
需要显示每个家长的详细信息以及他们的子女详细信息。
需要一些有价值的帮助。
英文:
I am having student data with two parents:
{
_id: ObjectId('643f8a6773a92fb1552e4c89'),
studentName: 'Peter Jackson',
studentId: 'SID1001',
grade: 2,
gender: 'Male',
parentDetails: [
{
_id: ObjectId('63fee5a42f60946679146768'),
name: 'Jackson Steve',
email: 'jack.steve@gmail.com',
mobile: 'xxxxxxxxxx',
relation: 'Father'
},
{
_id: ObjectId('6447c1ba22670472ed4b29cc'),
name: 'Amenda Jackson',
email: 'amenda.jack@gmail.com',
mobile: 'xxxxxxxxxx',
relation: 'Mother'
}
]
}
I need to show the student data based on each parent like below:
[
{
studentId: 'SID1001',
studentName: 'Peter Jackson',
grade: 2,
parentName: 'Jackson Steve',
parentEmail: 'jack.steve@gmail.com',
relation: 'Father'
},
{
studentId: 'SID1001',
studentName: 'Peter Jackson',
grade: 2,
parentName: 'Amenda Jackson',
parentEmail: 'amenda.jack@gmail.com',
relation: 'Mother'
}
]
Need to show individual parent details with their child details.
Need some valuable help.
答案1
得分: 3
-
$unwind
- 将parentDetails
数组拆分为多个文档。 -
$project
- 对输出文档进行修饰以获得所需的输出。
db.collection.aggregate([
{
$unwind: "$parentDetails"
},
{
$project: {
studentName: 1,
studentId: 1,
grade: 1,
parentName: "$parentDetails.name",
parentEmail: "$parentDetails.email",
relation: "$parentDetails.relation"
}
}
])
英文:
-
$unwind
- Deconstruct theparentDetails
array into multiple documents. -
$project
- Decorate the output document to desired output.
db.collection.aggregate([
{
$unwind: "$parentDetails"
},
{
$project: {
studentName: 1,
studentId: 1,
grade: 1,
parentName: "$parentDetails.name",
parentEmail: "$parentDetails.email",
relation: "$parentDetails.relation"
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论