Hi!
I have this scenario:
Doc01:
{
_id: "Unit123",
name: "Test Unit",
"sections": [
{
"_id": "63925553eeb147dc9bd894e1",
"name": "TestSection 1",
"contents": [
{
_id: "1",
"type": "TEXT_PAGE",
"pageTitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
"pageContent": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
},
{
_id: "2",
"type": "TEXT_PAGE",
"pageTitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
"pageContent": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}
],
},
],
},
Doc02:
{
"_id": "63925553eeb147dc9bd894e3",
unit: "Unit123",
user: 3,
lastContent: "2",
progressions: [
{
_id: "1",
isCompleted: true,
},
{
_id: "2",
isCompleted: true,
},
]
},
I want to achieve this structure:
{
_id: "Unit123",
name: "Test Unit",
"sections": [
{
"_id": "63925553eeb147dc9bd894e1",
"name": "TestSection 1",
"contents": [
{
_id: "1",
"type": "TEXT_PAGE",
"pageTitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
"pageContent": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"contentProgression": {
_id: "1",
isCompleted: true,
},
},
{
_id: "2",
"type": "TEXT_PAGE",
"pageTitle": "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
"pageContent": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"contentProgression": {
_id: "2",
isCompleted: true,
},
}
],
},
],
},
I’m stucked in turning the sections and contents a group after the lookup.
This is my query:
db.units.aggregate([
{
"$unwind": "$sections"
},
{
"$unwind": "$sections.contents"
},
{
"$lookup": {
"from": "unitProgressions",
let: {
contentsId: "$sections.contents._id"
},
pipeline: [
{
"$unwind": "$progressions"
},
{
$match: {
$expr: {
$eq: [
"$$contentsId",
"$progressions._id"
]
}
}
},
],
"as": "sections.contents.unitProgression"
}
},
{
"$unwind": {
path: "$sections.contents.unitProgression",
"preserveNullAndEmptyArrays": true
}
},
])
I tried to use group but it only groups the parent fields.
Is it possible to build this structure? Is there a better way to organize this schemas? It feels that I’ll have problems with this query speed.
Thanks!