一、数据准备
b.getCollection("log").drop();
db.createCollection("log");
db.getCollection("log").insert([{
_id: NumberLong("1117849502854676480"),
"event_level": NumberInt("3"),
ip: "27.196.85.144",
"operate_result": "成功",
"operate_time": ISODate("2023-06-12T08:14:50.000Z"),
"operate_type": NumberInt("30"),
"operator_name": "张三",
"account_type": NumberInt("1"),
}, {
_id: NumberLong("1117849502854676481"),
"event_level": NumberInt("3"),
ip: "27.196.85.144",
"operate_result": "成功",
"operate_time": ISODate("2023-06-12T08:14:50.000Z"),
"operate_type": NumberInt("30"),
operator_name": "张三",
"account_type": NumberInt("1"),
}, {
_id: NumberLong("1117849502854676482"),
"event_level": NumberInt("3"),
ip: "27.196.85.144",
"operate_result": "成功",
"operate_time": ISODate("2023-06-12T08:14:50.000Z"),
"operate_type": NumberInt("30"),
operator_name": "张三",
"account_type": NumberInt("1"),
}, {
_id: NumberLong("1117849502854676483"),
"event_level": NumberInt("3"),
ip: "27.196.85.144",
"operate_result": "成功",
"operate_time": ISODate("2023-06-12T08:14:50.000Z"),
"operate_type": NumberInt("30"),
operator_name": "张大",
"account_type": NumberInt("1"),
}, {
_id: NumberLong("1117849502854676484"),
"event_level": NumberInt("3"),
ip: "27.196.85.144",
"operate_result": "成功",
"operate_time": ISODate("2023-06-12T08:14:50.000Z"),
"operate_type": NumberInt("30"),
operator_name": "张三",
"account_type": NumberInt("1"),
}, {
_id: NumberLong("1117849502854676485"),
"event_level": NumberInt("3"),
ip: "27.196.85.144",
"operate_result": "成功",
"operate_time": ISODate("2023-06-12T08:14:50.000Z"),
"operate_type": NumberInt("30"),
operator_name": "张四",
"account_type": NumberInt("1"),
}]);
二、查询示例
db.log.aggregate([
{
$match: {
operate_type: 30, //操作类型为登录
"operate_time": { //查询时间范围
$gt: ISODate("2023-06-01 00:00:00"),
$lte: ISODate("2023-06-31 00:00:00")
},
},
},
{
$group: {
_id: { //以哪个字段分组,如果字段值不需要处理 _id:'$字段',
$dateToString: { //日期格式化函数
format: "%Y-%m-%d", //日期格式
date: "$operate_time" //格式化字段
},
},
loginCount: { //loginCount只是做为统计结果显示时的名字,有点类似as
$sum: 1
},
}
},
{
$sort:{
_id:1
}
}
,
{
$project:{ //最终返回字段配置,不配置该属性则只显示默认返回字段
"date":"$_id", //_id字段取别名
"loginCount":1 //表示结果显示该字段
}
}
]);
三、结果示例
四、java代码
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("operate_type").is(30)),//条件过滤
Aggregation.project("operate_time").and(DateOperators.DateToString.dateOf("operate_time").toString("%Y-%m-%d")).as("date"),
Aggregation.group("date").count().as("count"),
Aggregation.project("date", "count").and("date").previousOperation(),
Aggregation.sort(Sort.Direction.ASC, "date")
);
AggregationResults<LoginCountDTO> result = mongoTemplate.aggregate(aggregation, "log", LoginCountDTO.class);
math: 条件过滤,这个要放在第一行
project:显示哪几个字段,这里显示createTime字段,and..as是把and后的字段重命名为as后的字段,这里把createTime处理后重命名为date
group:分组操作,这里按date分组,计算数量,结果数量重命名为count
第二个project:previousOperation方法是把_id重命名为date(也就是别名)
sort:结果按照date正序排序 collectionName: 集合名称