Spring Boot MongoDB 聚合、去重、按日期分组
用户登陆数据存放在MongoDB中,每次登陆操作,都会插入一条记录,现在统计出,每天(指定时区)有多少个不同的用户登录成功
MongoDB中存的登录日志格式
{
"_id" : ObjectId("5da859dc062b4408b34555c8"),
"userId" : "79e1a83fc7e3407aaaf6dc7862461e4f",
"account" : "j111@163.com",
"loginResult" : "success",
"failReason" : "",
"ip" : "192.168.0.186",
"loginTime" : ISODate("2019-10-17T12:09:00.904+0000"),
}
代码实现
// 查询条件
Criteria criteria = Criteria
.where("loginResult").is(Constants.SUCCESS_STR);
// 格式化日期 YY-MM-DD,并且指定时区,Mongo不区分时区
AggregationExpression dateExpression = DateOperators.DateToString
.dateOf("loginTime")
.toString("%Y-%m-%d")
.withTimezone(
DateOperators.Timezone.valueOf("+08")
);
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.project("account")
.and(dateExpression).as("date"),
// 按日期和用户分组,去重用户,一个用户,一天只算一次
Aggregation.group("date", "account")
.first("date").as("date")
.first("account").as("account"),
// 统计按日期分组,统计每天登录的成功的总人数
Aggregation.group("date")
.count().as("loginUserNumber")
.first("date").as("date")
);
List<JSONObject> list = mongoTemplate.aggregate(aggregation, "USER_LOGIN_RECORD", JSONObject.class).getMappedResults();
System.out.println(JSON.toJSONString(list));
# 结果
[{"date":"2019-10-17","loginUserNumber":9,"_id":"2019-10-17"},{"date":"2019-10-18","loginUserNumber":8,"_id":"2019-10-18"}]