Spring Boot MongoDB 聚合、去重、按日期分组

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"}]
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值