Database
db={appointments:[{"userId":12,"status":"confirmed","appointments":[{"_id":"626aa028d4b154a3fcd8a9f4","forUser":{"whom":"other","id":"62624c25b58acc7728e3f8e6"},"appointmentType":"walkin","dates":{"createdAt":"2022-04-28T14: 09: 44.146Z","forDateAndShift":{"date":"2022-04-28T18: 30: 00.000Z","shift":ObjectId("623f484709fb21a7760ce18d")}},"status":"confirmed","serialNumber":3,"doctorId":ObjectId("626aa028d4b154a3fcd8a9f2"),"patientName":"something3"},{"_id":"62654e803c5d2bba0b799b3d","forUser":{"whom":"other","id":"626249c4b666dc59628502f2"},"appointmentType":"walkin","dates":{"createdAt":"2022-04-24T13: 20: 00.642Z","forDateAndShift":{"date":"2022-04-29T00: 00: 00.000Z","shift":ObjectId("623f484709fb21a7760ce188")}},"status":"confirmed","serialNumber":1,"doctorId":ObjectId("626aa028d4b154a3fcd8a9f2"),"patientName":"something1"},{"_id":"626a9f73d4b154a3fcd8a9b2","forUser":{"whom":"self","id":"6223370153c8126cd85884ce"},"appointmentType":"walkin","dates":{"createdAt":"2022-04-28T14: 06: 43.216Z","forDateAndShift":{"date":"2022-05-03T18: 30: 00.000Z","shift":ObjectId("623f484709fb21a7760ce188")}},"status":"confirmed","serialNumber":1,"doctorId":ObjectId("626aa028d4b154a3fcd8a9f2"),"patientName":"Manraj"}]},{"userId":12,"status":"completed","appointments":[{"_id":"62654e8e3c5d2bba0b799b5f","forUser":{"whom":"other","id":"626249c4b666dc59628502f2"},"appointmentType":"walkin","dates":{"createdAt":"2022-04-24T13: 20: 14.045Z","forDateAndShift":{"date":"2022-04-28T00: 00: 00.000Z","shift":ObjectId("623f484709fb21a7760ce188")}},"status":"completed","serialNumber":1,"doctorId":ObjectId("626aa028d4b154a3fcd8a9f2"),"patientName":"something1"}]}],doctors:[{"_id":ObjectId("626aa028d4b154a3fcd8a9f2"),"name":"ManrajSingh","profile":{"qualification":"MBBS","speciality":"Cardiologist","experience":5},timeSlots:[{_id:ObjectId("626aa028d4b154a3fcd8a9f1"),shifts:[{_id:ObjectId("623f484709fb21a7760ce18d"),time:ISODate("2022-04-28T14:09:44.146Z"),},{_id:ObjectId("623f484709fb21a7760ce188"),time:ISODate("2022-03-28T14:09:44.146Z"),}]}]}]}
Query
db.appointments.aggregate([{$match:{"userId":12}},{$lookup:{from:"doctors",localField:"doctorId",foreignField:"_id",let:{"shiftId":"$dates.forDateAndShift.shift"},pipeline:[{$match:{"timeSlots.shifts":{$elemMatch:{"_id":"$$shiftId"}}}}],as:"doctor"}}])