按日期范围计算的猫鼬操作

时间:2017-12-11 21:26:24

标签: mongodb mongoose

我有大量的时间序列数据,我希望每天都能获得。

例如,假设我想查询从3天到现在的日期范围。假设3天前有1000个错误,2天前有2000个错误,今天有500个错误。我的对象有一个'创建'日期字段。

为此,我可以做到

MyModel.count( { created: { $gte: threeDaysAgo, $lte: today } })

然后重复另外两天。当用户想要搜索300天的时间时,这就成了一个问题 - 我不得不做300次操作。所以我想跳过个别查询。

是否有Mongoose / MongoDB操作会将这些金额返还给我,而无需每天拨打个人电话?

1 个答案:

答案 0 :(得分:0)

我最终选择了聚合。这是我的代码:

             DBLogData.aggregate([
                {
                    $match: { application: application.id }
                },
                {
                    $group: {
                        _id: {
                           day: {
                              $dayOfMonth: "$created"
                          },
                          month: {
                              $month: "$created"
                          },
                          year: {
                              $year: "$created"
                          }
                      },
                        count: {
                            $sum: 1
                        }
                    }
                }
            ], (error, graphCountDatas) => {
                if (error) {
                    console.log(error);
                    callback(error);
                } else {
                    callback(null, graphCountDatas);
                }
            });

还有一些参考文献:

https://docs.mongodb.com/v3.4/aggregation/ https://docs.mongodb.com/v3.4/reference/operator/aggregation-date/