查询日期范围而不使用聚合在mongodb中使用循环

时间:2017-05-15 11:13:18

标签: mongodb

我有这些日期范围数组。这是我的wep应用程序中的图表功能。

[{
    "start": "7/01/2016",
    "end": "7/31/2016"
},{
    "start": "8/01/2016",
    "end": "8/31/2016"
},{
    "start": "9/01/2016",
    "end": "9/30/2016"
}]

这是我的样本数据。

    {
        "_id": 68,
        "charges": [
            {
                "id": "ch_1AD2wYHDsLEzoG2tjPo7uGnq",
                "amount": 1200,
               "created": "7/13/2016"
            },{
                "id": "ch_1ADPRPHDsLEzoG2t1k3o0qCz",
                "amount": 2000,
                "created": "8/1/2016"
            },{
                "id": "ch_1ADluFHDsLEzoG2t608Bppzn",
                "amount": 900,
                "created": "8/2/2016"
            },{
                "id": "ch_1AE8OWHDsLEzoG2tBmlm1A22",
                "amount": 1800,
                "created": "9/14/2016"
            }
        ]
    }

这是我试图实现的结果。

[
    {
        "created": "9/13/2016",
        "amount": 1200
    },{
        "created": "9/14/2016",
        "amount": 2900
    },{
        "created": "9/15/2016",
        "amount": 1800
    },
]

我可以在没有循环日期范围并查询内部的情况下实现这一目标吗?我只能设法做到这一点

    [
        {
            $match: { _id: 68 }
        },{
            $unwind: "$charges"
        },{
            I don't know what to do here
        }
    ]

注意:没关系日期格式

1 个答案:

答案 0 :(得分:1)

您可以使用mongodb 3.4中引入的新 $bucket 运算符来实现此目的:

db.collection.aggregate([  
   {  
      $match:{  
         _id:68
      }
   },
   {  
      $unwind:"$charges"
   },
   {  
      $bucket:{  
         groupBy:"$charges.created",
         boundaries:[  
            "7/01/2016",
            "8/01/2016",
            "9/01/2016",
            "9/30/2016"
         ],
         default:"others",
         output:{  
            amount:{  
               $sum:"$charges.amount"
            }
         }
      }
   }
])

解释:

  1. 使用 $match
  2. 匹配特定文档
  3. 展开charges数组
  4. 按范围分组(范围在boundaries中提供)
  5. 此输出:

    { "_id" : "7/01/2016", "amount" : 1200 }
    { "_id" : "8/01/2016", "amount" : 2900 }
    { "_id" : "9/01/2016", "amount" : 1800 }