I have a double nested document and I need to $lookup it with the other collection. For that I unwind the document, then do the $lookup and I have struck here. I cannot 'un-unwind' it.
I am struck here:
mongoose.aggregate([
{ "$match": { "weekNumber": weekNumber } },
{ "$unwind": "$locations" },
{ "$addFields": { "shifts": "$locations.shifts"}},
{ "$unwind": "$shifts" },
{ "$lookup": {
"let": { "userObjId": { "$toObjectId": "$shifts.shiftTypeId" } },
"from": "shiftTypes",
"pipeline": [
{ "$match" : { "$expr": { "$eq" : [ "$_id", "$$userObjId"] } } }
],
"as": "shiftType"
}
},
{ "$addFields": {
"shifts.name": "$shiftType.name",
"shifts.color": "$shiftType.color"
}
},
{ "$project": {
"shiftType": 0,
"locations.shifts": 0
}
}
])
Currently I have unwinded object with all the necessary fields, but cannot 'pack' them back together.
I have a collections - planning - with the following:
[
{
_id: ObjectId(),
"weekNumber": 30,
"locations": [
{
"location": "locationName1",
"shifts": [
{
"shiftTypeId": "shiftType001",
},
{
"shiftTypeId": "shiftType002",
},
{
"shiftTypeId": "shiftType001",
}
]
},
{
"location": "locationName2",
"shifts": [
{
"shiftTypeId": "shiftType001",
},
{
"shiftTypeId": "shiftType002",
},
{
"shiftTypeId": "shiftType001",
}
]
},
{
"location": "locationName3",
"shifts": [
{
"shiftTypeId": "shiftType001",
},
{
"shiftTypeId": "shiftType002",
},
{
"shiftTypeId": "shiftType001",
}
]
}
]
}
]
and I have another collection - shiftTypes - like
[
{
_id: ObjectId("shiftType001"),
"name": "shift001",
"color": "red"
},
{
_id: ObjectId("shiftType002"),
"name": "shift002",
"color": "blue"
}
]
What I would like to achive is this:
[
{
_id: ObjectId(),
"weekNumber": 30,
"locations": [
{
"location": "locationName1",
"shifts": [
{
"shiftTypeId": "shiftType001",
"name": "shift001",
"color": "red"
},
{
"shiftTypeId": "shiftType002",
"name": "shift002",
"color": "blue"
},
{
"shiftTypeId": "shiftType001",
"name": "shift001",
"color": "red"
}
]
},
{
"location": "locationName2",
"shifts": [
{
"shiftTypeId": "shiftType002",
"name": "shift002",
"color": "blue"
},
{
"shiftTypeId": "shiftType002",
"name": "shift002",
"color": "blue"
},
{
"shiftTypeId": "shiftType001",
"name": "shift001",
"color": "red"
}
]
},
{
"location": "locationName3",
"shifts": [
{
"shiftTypeId": "shiftType001",
"name": "shift001",
"color": "red"
},
{
"shiftTypeId": "shiftType001",
"name": "shift001",
"color": "red"
},
{
"shiftTypeId": "shiftType001",
"name": "shift001",
"color": "red"
}
]
}
]
}
]
Thanks for your help in advance