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
{
$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
[
{
"_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"
]
}
]
}
]
}
]