下面是我的代码
let startDateTimeStr = start_date + "T00:00:00.0000000"; // Making sure to match the number of zeros in the format
let endDateTimeStr = end_date + "T00:00:00.0000000";
matchCase.push({
"start.dateTime": {
$gte: startDateTimeStr,
},
"end.dateTime": {
$lte: endDateTimeStr,
},
});
我需要从其他数据库中获取数据。我想要的是,从我的领域,我想选择其状态被拒绝的电子邮件ID。在appointments集合中,架构如下所示:
attendees包含一系列文档,其中包含响应字段和电子邮件地址字段。
地址包含电子邮件地址。如果拒绝,则根据响应进行选择。
然后在用户集合中查找匹配的电子邮件地址,并在那里返回user_serial_id,但它什么也没有返回。下面是我的完整代码
matchCase.push({
"start.dateTime": {
$gte: startDateTimeStr,
},
"end.dateTime": {
$lte: endDateTimeStr,
},
});
matchCase.push({
"attendees.status.response": { $ne: "declined" },
});
let addFieldsQuery = {
$addFields: {
nonDeclinedEmails: {
$map: {
input: {
$filter: {
input: "$attendees",
as: "attendee",
cond: { $ne: ["$$attendee.status.response", "declined"] }
}
},
as: "nonDeclined",
in: "$$nonDeclined.email"
}
}
}
};
let lookupQuery = {
$lookup: {
from: "users",
localField: "nonDeclinedEmails",
foreignField: "email",
as: "nonDeclinedUsers"
}
};
let projectQuery = {
$project: {
user_id: 1,
description: 1,
title: "$subject",
start: "$start.dateTime",
end: "$end.dateTime",
type: "appointment",
resource: "$nonDeclinedUsers.user_serial_id", // populated from lookup
recurrence: "$recurrence",
editable: { $toBool: 0 }
}
};
let aggregatQuery = [];
if (matchCase.length > 0) {
aggregatQuery.push({
$match: {
$and: matchCase
}
});
}
aggregatQuery.push(addFieldsQuery); // add fields for non-declined emails
aggregatQuery.push(lookupQuery); // perform lookup to get autotask_id
if (Object.keys(projectQuery).length > 0) {
aggregatQuery.push(projectQuery);
}
console.log(`User id is ${userId}`);
return aggregatQuery;
然后我执行这段代码
let appointmentsQry = await AppointmentsQuery(req, res);
appointments = await appointmentsModel.aggregate(appointmentsQry).exec();
1条答案
按热度按时间ocebsuys1#
在$lookup阶段,本地字段是
nonDeclinedEmails
,它是一个数组,外部字段是email
。这将只匹配用户集合中的文档,这些文档的电子邮件字段完全包含(包括相同的顺序)nonDeclinedEmails列表。
您可能需要先展开nonDeclinedEmails列表。