我有一个Event
文档结构如下,我正在尝试查询employeeResponses
用于收集单个员工的所有响应(可能存在也可能不存在)的数组:
[
{
...
eventDate: 2019-10-08T03:30:15.000+00:00,
employeeResponses: [
{
_id:"5d978d372f263f41cc624727",
response: "Available to work.",
notes: ""
},
...etc
];
}
];
我当前的猫鼬聚合是:
const eventResponses = await Event.aggregate([
{
// find all events for a selected month
$match: {
eventDate: {
$gte: startOfMonth,
$lte: endOfMonth,
},
},
},
{
// unwind the employeeResponses array
$unwind: {
path: "$employeeResponses",
preserveNullAndEmptyArrays: true,
},
},
{
$group: {
_id: null,
responses: {
$push: {
// if a response id matches the employee's id, then
// include their response; otherwise, it's a "No response."
$cond: [
{ $eq: ["$employeeResponses._id", existingMember._id] },
"$employeeResponses.response",
"No response.",
],
},
},
},
},
{ $project: { _id: 0, responses: 1 } },
]);
您无疑会注意到,在超过 1 名员工记录响应后,上面的查询将不起作用,因为它将每个单独的响应视为 T/F 条件,而不是所有的回应内employeeResponses
数组作为单个 T/F 条件。
因此,我删除了初始查询后的所有后续查询$match
并进行手动减少:
const responses = eventResponses.reduce((acc, { employeeResponses }) => {
const foundResponse = employeeResponses.find(response => response._id.equals(existingMember._id));
return [...acc, foundResponse ? foundResponse.response : "No response."];
}, []);
我想知道是否有可能达到上面相同的减少结果,但也许使用 mongo$reduce
功能?或者重构上面的聚合查询来处理employeeResponses
作为单一 T/F 条件?
此聚合的最终目标是从每个找到的员工中提取任何先前记录的员工的响应和/或缺少响应的内容Event
当月内并将他们的响应放入单个数组中:
["I want to work.", "Available to work.", "Not available to work.", "No response.", "No response." ...etc]