[英]How to unwind nested object arrays in mongodb aggregation?
I have some data with an array of objects which contains another array.我有一些包含另一个数组的对象数组的数据。 I am trying to unwind the courses array then the requirements array to match subjects then group everything back together.
我正在尝试展开课程数组,然后展开需求数组以匹配主题,然后将所有内容组合在一起。
So far I can work fine with the courses array.到目前为止,我可以很好地使用课程数组。 But I just can't get around doing the same thing for the second array requirements .
但我就是无法为第二个数组要求做同样的事情。
[
{
"_id": 1,
"name": "provider name",
"courses": [
{
"_id": 1,
"name": "course name",
"requirements": [
{
"subjects": [
"SubjectA::B",
"SubjectB::B",
"SubjectC::B"
]
},
{
"subjects": [
"SubjectA::B",
"SubjectB::B",
"SubjectC::B"
]
}
]
}
]
}
]
First I unwind both arrays首先我解开 arrays
{
$unwind: {
path: '$courses',
preserveNullAndEmptyArrays: true
}
},
{
$unwind: {
path: '$courses.requirements',
preserveNullAndEmptyArrays: true
}
},
How I group the first array我如何对第一个数组进行分组
{
$group: {
_id: '$_id',
root: { $mergeObjects: '$$ROOT' },
courses: { $push: '$courses' }
}
},
{
$replaceWith: {
$mergeObjects: ['$root', '$$ROOT'],
}
},
{
$project: { root: 0 }
},
Expected Output预计 Output
[
{
"_id": 1,
"name": "provider name",
"courses": [
{
"_id": 1,
"name": "course name",
"requirements": [
{
"subjects": [
"SubjectA::B",
"SubjectB::B",
"SubjectC::B"
]
},
{
"subjects": [
"SubjectA::B",
"SubjectB::B",
"SubjectC::B"
]
}
]
}
]
}
]
But I get但我明白了
[
{
"_id": 1,
"name": "provider name",
"courses": [
{
"_id": 1,
"name": "course name",
"requirements": [
{
"subjects": [
"SubjectA::B",
"SubjectB::B",
"SubjectC::B"
]
},
{
"subjects": [
"SubjectA::B",
"SubjectB::B",
"SubjectC::B"
]
}
]
},
{
"_id": 1,
"name": "course name",
"requirements": [
{
"subjects": [
"SubjectA::B",
"SubjectB::B",
"SubjectC::B"
]
},
{
"subjects": [
"SubjectA::B",
"SubjectB::B",
"SubjectC::B"
]
}
]
}
]
}
]
You can reconstruct tour arrays by below stages,您可以通过以下阶段重建游览 arrays,
$group
by _id
and courses._id
and get first name
and course first name, and construct the requirements
array $group
by _id
和courses._id
得到name
和课程名字,并构造requirements
数组$group
by only _id
and get first name
and reconstruct courses
array $group
by only _id
并获取name
并重建courses
数组 {
$group: {
_id: {
_id: "$_id",
cId: "$courses._id"
},
name: { $first: "$name" },
course_name: { $first: "$courses.name" },
requirements: { $push: "$courses.requirements" }
}
},
{
$group: {
_id: "$_id._id",
name: { $first: "$name" },
courses: {
$push: {
_id: "$_id.cId",
name: "$course_name",
requirements: "$requirements"
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.