如何过滤$ lookup结果

时间:2018-12-13 18:01:59

标签: mongodb mongoose mongodb-query aggregation-framework lookup

我有一个查询,我使用$lookup,在此查询中,我需要传递一个参数以基于字段scheduleStart“过滤”结果(我使用了moment.js将日期传递给我的查询)。我不知道应该在哪里传递参数。

我的查询

   User.aggregate([{
          $match: {
            storeKey: req.body.store,     
          }
        },
        {
          $group: {
            _id: {
              id: "$_id",
              name: "$name",
              cpf: "$cpf",      
              phone: "$phone",
              email: "$email",
              birthday: "$birthday",
              lastName: "$lastname"      
            },
            totalServices: {
              $sum: "$services"
            },    
          }
        },
        {
          $lookup: {
            from: "schedules",
            "let": { "id": "$_id.phone" },
            "pipeline": [
               { "$match": { "$expr": { "$eq": ["$customer.phone", "$$id"] }}},
               { "$project": { "scheduleStart": 1, "scheduleEnd": 1, "value": 1 }}
            ],
            "as": "user_detail"
          }  
        },  
        {
          $project: {
            _id: 1,
            name: 1,
            name: 1,
            cpf: 1,      
            phone: 1,
            email: 1,
            birthday: 1,
            totalServices: 1,
            totalValue: { $sum : "$user_detail.value" },      
            count: {
              $sum: 1
            },
            user_detail: 1
          }
        },

我要在该查询中传递的参数:

 start = '2018-12-13 00:00'
 period = '2017-01-13 00:00'

查询的实际结果:

6:
count: 1
totalServices: 0
totalValue: 73
user_detail: Array(2)
0: {_id: "5bb2832890c4f23d207b5d71", scheduleStart: "2018-10-02 08:20", scheduleEnd: "2018-10-02 08:40", value: 40}
1: {_id: "5bfd9c13e1193a4f30df05e4", scheduleStart: "2018-11-27 00:03", scheduleEnd: "2018-11-27 00:13", value: 33}

_id: {id: "5bfed8bd70de7a383855f09e", name: "Chris Santos G", phone: "11969109995", email: "csantosgrossi@gmail.com", birthday: "1992-03-06"}

如何传递参数以scheduleStart的结果进行过滤?我不知道我是否需要传递$ lookup或之后的内容。

1 个答案:

答案 0 :(得分:1)

您可以使用$lookup$lte查询运算符在$match阶段的$gte管道内使用过滤器

{ "$lookup": {
  "from": "schedules",
  "let": { "id": "$_id.phone" },
  "pipeline": [
    { "$match": {
      "$expr": { "$eq": ["$customer.phone", "$$id"] },
      "scheduleStart": {
        "$lte": moment("2018-12-13 00:00").toDate(),
        "$gte": moment("2017-01-13 00:00").toDate()
      }
    }},
    { "$project": { "scheduleStart": 1, "scheduleEnd": 1, "value": 1 }}
  ],
  "as": "user_detail"
}}