MongoDB按日期分组
**存入MongoDB的数据有个报表需求,根据传入一个时间段,能够按天、按月汇总统计。需求不难,如果用MySQL分分钟的事情;但是对MongoDB聚合查询不太熟悉,一直在寻找MongoDB的格式化分组,也没找到。
想快速完成有2种方案:
- 全部查出来,在代码里面用jdk8新特性->stream直接分组;但是考虑到最大范围一年的数据,有可能撑爆内存且消耗资源,不采纳。
- 根据汇总的维度,循环count;查询维度是月,一个月最多31天,并发不大count 31次好像也能接受;一年最大12个月,count 12次更加没问题。时间太过于敢了,只能先用这个方案应付。
终于尝试到了MongoDB格式化日期后再分组的脚本,实操后验证没问题。马上替换代码,效率隐患排除。
下面给出Demo
插入数据
点击查看代码
db.getCollection("alarm").insert( {
level: 1,
time: ISODate("2022-07-12T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 2,
time: ISODate("2022-07-11T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 2,
time: ISODate("2022-07-01T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 1,
time: ISODate("2022-07-01T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 1,
time: ISODate("2022-07-11T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 2,
time: ISODate("2022-07-11T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 3,
time: ISODate("2022-08-02T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 1,
time: ISODate("2022-08-02T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 2,
time: ISODate("2022-08-02T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 1,
time: ISODate("2022-08-12T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 3,
time: ISODate("2022-07-12T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 3,
time: ISODate("2022-08-11T00:00:00.000Z")
} );
db.getCollection("alarm").insert( {
level: 3,
time: ISODate("2022-07-11T00:00:00.000Z")
} );
查询脚本
点击查看代码
db.alarm.aggregate([{
$project: {
month: {
// $month: "$time"
$dateToString: {
format: "%Y-%m",
date: "$time"
}
},
level: 1
}
}, {
$group: {
_id: {
month: "$month",
level: "$level"
},
CountValue: {
$sum: 1
}
}
}])
结果展示
点击查看代码
// 1
{
"_id": {
"month": "2022-08",
"level": 3
},
"CountValue": 2
}
// 2
{
"_id": {
"month": "2022-07",
"level": 1
},
"CountValue": 3
}
// 3
{
"_id": {
"month": "2022-07",
"level": 2
},
"CountValue": 3
}
// 4
{
"_id": {
"month": "2022-08",
"level": 2
},
"CountValue": 1
}
// 5
{
"_id": {
"month": "2022-07",
"level": 3
},
"CountValue": 2
}
// 6
{
"_id": {
"month": "2022-08",
"level": 1
},
"CountValue": 2
}