I need to look up ObjectIDs in nested arrays of objects. Here is what I got so far:
.Shift.aggregate([
{ $match: { startDate: { $gte: lowerDate, $lte: upperDate} } },
{ $group: {_id: '$team', shifts: { $addToSet: '$_id' } } },
{ $lookup: {from: 'teams', localField: '_id', foreignField: '_id', as: 'team' }},
{ $lookup: {from: 'shifts', localField: 'shifts', foreignField: '_id', as: 'shifts' }}])
.exec(function (err, teamShifts) {...
This is what i have now
[
...
{
"_id": "60a277b05c7462f42b3d788c",
"shifts": [
{
"_id": "60a62116ead409441bd112",
"assignedUser": "60a36baddf6a04c72b2d9f",
"team": "60a277b05c7462f43d788c",
"shiftType": "60a278357462f42b3d7895",
"startDate": 1621641600000,
"endDate": 1622246400000,
"__v": 0
},
{
"_id": "60a679a03525cec3f86949",
"assignedUser":
...
},
...
],
"team": [
{
"_id": "60a277b05c62f42b3d788c",
"name": "a team name",
"owner": "60a26e6c91273a938690b2",
"description": "a description",
}
]
},
...
]
for example I am trying to populate the "assignedUser" with the "_id" from another document "users"
But adding this does not produce the result I need:
{ $lookup: {from: 'users', localField: 'shifts.assignedUser', foreignField: '_id', as: 'shifts.assignedUser' }},
What do I need to do to lookup / populate IDs nested in the data?
I tried unwind but that makes it harder to group by team, also it's not need for this anymore as i read (we are running mongodb 4.4.3). I probably need piplines(?) but I have trouble using the docs for my case.