mongodb基于子子文档的数组

时间:2017-05-18 00:50:45

标签: angularjs mongodb mongoose

我试图从志愿者收集中获取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"})

1 个答案:

答案 0 :(得分:2)

您可以尝试以下聚合查询

$match查找包含volunteers email

的文档 <{> $project $arrayElemAtshift数组转换为文档,然后$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"
    }
})