如何过滤$ lookup结果

马修斯·巴伦(Matheus Barem)

我有一个查询,我使用$ 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: "[email protected]", birthday: "1992-03-06"}

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

阿什

您可以$lookup$match阶段内使用$lte$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"
}}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章