預約樣本資料
{
"doctorId": "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": "623f484709fb21a7760ce188"
}
},
"status": "confirmed",
"_id": "626cee063558d4a281fcccdb",
}
醫生樣本資料
"name": "Someone",
"profile": {
"qualification": "MBBS",
"speciality": "Cardiologist",
"experience": 5
},
"timeSlots": [
{
"day": "3",
"shifts": [
{
_id:"623f484709fb21a7760ce188"
"maximumAllowedAppointments": 30,
"startTime": {
"hours": "9",
"minutes": "0"
},
"endTime": {
"hours": "12",
"minutes": "0"
}
},
]
},
想要獲得與預約輪班 id 匹配的醫生輪班時間,嘗試使用管道并讓內部查找,除了空陣列之外沒有提供任何輸出。查詢試圖實作相同
appointment.aggregate([
{ $match: { userId: user._id } },
{ $sort: { "dates.forDateAndShift.date": 1 } },
{
$lookup: {
from: "doctors",
localField: "doctorId",
foreignField: "_id",
let: { shiftId: "$dates.forDateAndShift.shift" },
pipeline: [
{ $match: { "timeSlots.shifts": { $elemMatch: { _id: "$$shiftId" } } } }
],
as: "doctor"
}
},
{ $unwind: "$doctor" },
{
$project: {
status: 1,
forUser: 1,
dates: 1,
serialNumber: 1,
"doctor.name": 1,
appointmentType: 1,
"doctor.profile": 1
}
},
{ $group: { _id: "$status", appointments: { $push: "$$ROOT" } } },
{ $project: { _id: 0, status: "$_id", appointments: "$appointments" } }
])
我寫這個問題的這一部分是為了避免所有代碼都來自堆疊溢位的警告,因此請您忽略本節
uj5u.com熱心網友回復:
獲得正確轉變的一種方法doctor
是:
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"
}
},
// TODO: continue your query
])
您可以在這個游樂場示例中看到它是如何作業的。
如果 shift_id 是唯一的,您可以$lookup
使用以下命令繼續管道:
{$project: {shifts: {$arrayElemAt: ["$shifts", 0]}}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470270.html
上一篇:MongoDB查找嵌套屬性
下一篇:如何查找和更新檔案陣列中的物件