Mongodb java api 调用

本文分享了使用MongoDB存储并分析网站访问日志的方法,包括核心代码示例及聚合查询技巧,强调了正确顺序应用$match和$group的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景: 使用mongo 存网站访问日志 ,并对其统计分析 。

核心代码如下:

  Bson liveBson = Filters.and(Filters.gte("time", strToLongSafe(start)), Filters.lte("time", strToLongSafe(end))
                        , Filters.eq("response_code", "200"),
                        Filters.regex("url", "/register/"),
                        Filters.regex("referrer", "www.xiucai.com/live/\\d+"));
                collection.find(liveBson).forEach((Consumer<? super Document>) item -> {
                    System.out.println(item);
                });
                Document filter = new Document();
                filter.append("time", new Document("$gte", strToLongSafe(start)));
                filter.append("time", new Document("$lte", strToLongSafe(end)));
                filter.append("response_code", new Document("$eq", "200"));
                filter.append("url", new Document("$regex", "/register/"));
                filter.append("referrer", new Document("$regex", "www.xiucai.com/live/\\d+"));

                Document group = new Document();
                group.append("_id", "$channel");//根据渠道来分组
                group.append("count", new Document("$sum", 1));
                Document match = new Document("$match", filter);
                Document groupd = new Document("$group", group);
                List docList = new ArrayList();
                docList.add(match);
                docList.add(groupd);//注意先match 后 group by 
                collection.aggregate(docList).forEach((Consumer<? super Document>) item -> {
                    System.out.println(item);
                });

遇到的坑: 使用 aggregate 聚合如果把聚合的顺序写反 $group  在前  $match 在后 得不到数据  ,

编码小窍门: 类SQL一样先 where   后 group by  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值