我试图从志愿者收集中获取Mary Mack所有班次的名单,但我一直都没有回来。有人可以帮帮我吗?我尝试了几种方法,其中一些方法如下所示。
我希望数据看起来像:
where date time details
__________________________________________________________
Registration 2017-06-24 8AM - NOON check people in
我的志愿者数据看起来像这样:
{
where: "Registration",
description: "blah blah blah",
shifts: [{
dateNeeded: "2017-06-24",
timeslot: "8AM - NOON",
details: "check people in",
volunteers: [{
name: "Mary Mack",
phone: 1234567890,
email: "mary@mack.com"
}]
}]
}
我试过了:
Volunteer.find({"shifts.volleyteers.email": "mary@mack.com" }, { "shifts.$": 1, "where": 1 })
我也尝试过聚合和过滤:
Volunteer
.aggregate(
{$project: {where:1, shifts:1}},
{$unwind: "$shifts"})
答案 0 :(得分:2)
您可以尝试以下聚合查询
$match
查找包含volunteers
email
$project
$arrayElemAt
将shift
数组转换为文档,然后$let
映射输出字段。
aggregate({
$match: {
"shifts.volunteers.email": "mary@mack.com"
}
}, {
$project: {
where: 1,
shifts: {
$let: {
vars: {
doc: {
$arrayElemAt: ["$shifts", 0]
}
},
in: {
date: "$$doc.dateNeeded",
time: "$$doc.timeslot",
details: "$$doc.details"
}
}
}
}
})
您还可以添加额外的$project
阶段而不是$let
运算符。
aggregate({
$match: {
"shifts.volunteers.email": "mary@mack.com"
}
}, {
$project: {
where: 1,
shift: {
$arrayElemAt: ["$shifts", 0]
}
}
}, {
$project: {
where: 1,
date: "$shift.dateNeeded",
time: "$shift.timeslot",
details: "$shift.details"
}
})