I have 3 collections as follows:
I would like to have all the available appointments for a doctor which are not in the appointments collection. I have tried the following query and been working on it from hours:
const appointments = await Doctor.aggregate([
{$match: {role: 'DOCTOR', _id: ObjectId(doctorId)}},
{
$lookup: {
from: 'professionalDetails',
localField: '_id',
foreignField: 'doctorId',
as: 'professionalDetails'
}
},
{
$lookup: {
from: 'appointments',
localField: '_id',
foreignField: 'doctorId',
as: 'appointments'
}
},
{$unwind: "$professionalDetails"},
{$unwind: "$professionalDetails.schedule"},
{$match: {'professionalDetails.schedule.day': 'Tuesday'}},
{$unwind: "$professionalDetails.schedule.timmings"},
{$unwind: "$appointments"},
{$match: {'professionalDetails.schedule.timmings._id': {$ne: 'appointments.slotId'}}},
{
$project: {
_id: 0,
time: '$professionalDetails.schedule.timmings.slot',
_id: '$professionalDetails.schedule.timmings._id'
}
}
]);
The above still returns all the slots. However if I hardcode the not equal match as follows it works:
{$match: {'professionalDetails.schedule.timmings._id': {$ne: ObjectId('5dd2a9cab4a4a32c9359ac1f')}}}
Also both the ids are Object Ids in the mongoose model and not strings.
I am pretty new to it. Guidance is really appreciated!
Please help! Thanks in advance!
I tried adding $appointments.slotId as Tom suggested however that did not work out too.
After trying and looking around. Finally I got the output I was looking for after replacing the match statement with the following:
{
$match: {
$expr: {$ne: ['$professionalDetails.schedule.timmings._id', '$appointments.slotId']}
}
}
Any improvements or suggestions are still welcomed!