Database
db={appointment:[{"doctorId":ObjectId("623f484709fb21a7760ce187"),"userId":"6223370153c8126cd85884ce","forUser":{"whom":"other","id":"626249c4b666dc59628502f2"},"appointmentType":"walkin","dates":{"createdAt":"2022-04-30T08:06:30.066Z","forDateAndShift":{"date":"2022-05-02T00:00:00.000Z","shift":ObjectId("623f484709fb21a7760ce188")}},"status":"confirmed","_id":"626cee063558d4a281fcccdb",},{"doctorId":ObjectId("623f484709fb21a7760ce187"),"userId":"6223370153c8126cd85884ce","forUser":{"whom":"other","id":"626249c4b666dc59628502f2"},"appointmentType":"walkin","dates":{"createdAt":"2022-04-30T08:06:30.066Z","forDateAndShift":{"date":"2022-05-02T00:00:00.000Z","shift":ObjectId("623f484709fb21a7760ce184")}},"status":"cancelled","_id":"626cee063558d4a281fcccde",}],doctors:[{_id:ObjectId("623f484709fb21a7760ce187"),"name":"Someone","profile":{"qualification":"MBBS","speciality":"Cardiologist","experience":5},"timeSlots":[{"day":"3","shifts":[{_id:ObjectId("623f484709fb21a7760ce188"),"maximumAllowedAppointments":30,"startTime":{"hours":"9","minutes":"0"},"endTime":{"hours":"12","minutes":"0"}},{_id:ObjectId("623f484709fb21a7760ce189"),"maximumAllowedAppointments":30,"startTime":{"hours":"9","minutes":"0"},"endTime":{"hours":"12","minutes":"0"}}]},{"day":"4","shifts":[{_id:ObjectId("623f484709fb21a7760ce184"),"maximumAllowedAppointments":30,"startTime":{"hours":"9","minutes":"0"},"endTime":{"hours":"12","minutes":"0"}},{_id:ObjectId("623f484709fb21a7760ce182"),"maximumAllowedAppointments":30,"startTime":{"hours":"9","minutes":"0"},"endTime":{"hours":"12","minutes":"0"}}]}]}]}
Query
db.appointment.aggregate([{$match:{userId:"6223370153c8126cd85884ce"}},{$sort:{"dates.forDateAndShift.date":1}},{$lookup:{from:"doctors",let:{shiftId:"$dates.forDateAndShift.shift",doctorId:"$doctorId"},pipeline:[{$match:{$expr:{$eq:["$_id","$$doctorId"]}}},{$unwind:"$timeSlots"},{$project:{_id:0,shifts:{$filter:{input:"$timeSlots.shifts",as:"item",cond:{$eq:["$$item._id","$$shiftId"]}}}}},{"$addFields":{"shiftsCount":{$size:"$shifts"}}},{$match:{shiftsCount:{$gt:0}}},{$unset:"shiftsCount"}],as:"doctor"},},])