我的mongodb聚合查询应返回特定日期范围内的每日,每周,每月,每年的数据。
示例:假设日期为2月1日至3月1日。
每日数据应为:1、2、3。 每周期间是:2月1日,2月8日,2月15日,2月22日.. 每月的时间是2月1日,3月1日。
看下面的例子:
假设我的API接受:startDate,endDate,interval作为主体参数。
req.body将是这样的:
{
startDate: "",
endDate: "",
platform: "",
interval: "daily" // could be "weekly", "monthly", "yearly"
}
这些参数将传递到我的模型中,在这里我将有一些聚合代码,将在下面提到:
MessagesSchema.statics.totalMessages = ( startDate, endDate, platform, interval ) => {
return Messages.aggregate([{
$match: {
platform: platform,
timestamp: {
$gte: new Date(startDate),
$lte: new Date(endDate)
}
}
},
{
$project: {
timestamp: {
$dateToString: {
format: '%Y-%m-%d',
date: '$timestamp'
}
}
}
},
{
$group: {
_id: {
timestamp: '$timestamp'
},
count: {
$sum: 1
}
}
},
{
$sort: {
'_id.timestamp': 1
}
}
]).exec();
让我们假设从2019年2月1日到2019年3月1日为每周数据;
预期结果:
[
{
"_id": {
"timestamp": "2019-02-01"
},
"count": 2
},
{
"_id": {
"timestamp": "2019-02-08"
},
"count": 2
},
{
"_id": {
"timestamp": "2019-02-15"
},
"count": 2
}
]
实际结果:
[
{
"_id": {
"timestamp": "2019-02-01"
},
"count": 2
},
{
"_id": {
"timestamp": "2019-03-02"
},
"count": 2
},
{
"_id": {
"timestamp": "2019-03-02"
},
"count": 2
}
]