这两天要做mongodb日志的模块,下面记录一下。

一、

首先要导入一批数据,使用springboot来完成。

配置mongodb的复制集:在application.yml文件中配置uri来完成

格式:mongodb://用户名:密码@ip:端口[,ip:端口] [,ip:端口]/数据库名

下面注入mongoTemplate:

二、

Mongodb在java中分组使用应该有两三种方式:可以百度一下

下面我贴上我们项目组使用的代码:

@Service("logMongoService")

public class LogMongoServiceImpl implements LogMongoService {

/**

* 按月统计登录次数使用的初始化的js对象

*/

private static final String initMonthGroupByJs = "{total:0," +

"JanCount:0," +

"FebCount:0," +

"MarCount:0," +

"AprCount:0," +

"MayCount:0," +

"JuneCount:0," +

"JulyCount:0," +

"AugCount:0," +

"SepCount:0," +

"OctCount:0," +

"NovCount:0," +

"DecCount:0}";

/**

* 按月统计登录次数使用的js,mongodb在执行时会自动的执行此脚本

*/

private static final String monthGroupByJs =

"function(doc, prev){" +

"prev.total += 1;" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 0) {" +

"prev.JanCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 1) {" +

"prev.FebCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 2) {" +

"prev.MarCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 3) {" +

"prev.AprCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 4) {" +

"prev.MayCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 5) {" +

"prev.JuneCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 6) {" +

"prev.JulyCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 7) {" +

"prev.AugCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 8) {" +

"prev.SepCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 9) {" +

"prev.OctCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 10) {" +

"prev.NovCount += 1;" +

"}" +

"if (doc.startTime.getFullYear() == searchYear && doc.startTime.getMonth() == 11) {" +

"prev.DecCount += 1;" +

"}" +

"}";

@Override

public void findMonthLogin(MongoPage page, SystemLogQuery systemLogQuery) throws Exception{

//添加年份的限制  也就是查询条件

Criteria[] logType ={Criteria.where("logType").is("2")};

Calendar startCalendar = Calendar.getInstance();

startCalendar.set(year, 0, 1, 0,0, 0);

Calendar endCalendar = Calendar.getInstance();

endCalendar.set(year + 1, 0, 1, 0,0, 0);

Criteria[] yearCriteria ={Criteria.where("startTime").gte(startCalendar.getTime()).lt(endCalendar.getTime())};

logType = (Criteria[]) ArrayUtils.addAll(logType, yearCriteria);

//组织分组时使用的js

String initGroupByJs = initMonthGroupByJs;

String groupByJs = monthGroupByJs.replace("searchYear", year + "");

//此处开始分组查询

//以name字段进行分组

GroupBy groupBy = new GroupBy("username","name","departmentName").

initialDocument(initGroupByJs).

reduceFunction(groupByJs);

//执行分组查询

GroupByResults groupByResults = logMongoDao.group(new Criteria().andOperator(logType), groupBy);

//取出分组后的数据 这里必须是retval

BasicDBList list = (BasicDBList) groupByResults.getRawResults().get("retval");

page.setTotal(list.size());

//用来存放查询到的list集合

List<SystemLogVO> logVOList = new ArrayList<SystemLogVO>();

for (int i = (page.getPageNumber()-1) * page.getPageSize();

i < page.getPageNumber() * page.getPageSize() && i < list.size(); i++) {

SystemLogVO systemlog = new SystemLogVO();

//在这个obj中就包含了所有的分组后,我们自定义的哪些属性的值

BasicDBObject obj = (BasicDBObject)list.get(i);

systemlog.setName(obj.get("name") == null? "" : obj.get("name").toString());

systemlog.setDepartmentName(obj.get("departmentName") == null?"":obj.get("departmentName").toString());

systemlog.setUsername(obj.get("username") == null?"":obj.get("username").toString());

//获取其中的月份的值

obj.get("total");//总的值

obj.get("JanCount");//根据条件过滤后,统计的1月份的值

obj.get("DecCount");

}

}

}

需要说明的一点是,groupByJs这个是一个回调函数,

当mongodb在过滤数据时,会调用这个js方法,doc变量是将正在处理的一条数据传输进来,prev相当于上面定义的initMonthGroupByJs中的js对象,

最后在initMonthGroupByJs中定义的对象会返回给我们,我们可以从prev中取到我们所有需要的数据。

Addition:

https://blog.csdn.net/liming_0820/article/details/78657146

http://www.cnblogs.com/anhaogoon/p/9354248.html

mongodb分组函数的使用(spring-data-mongodb)的更多相关文章

  1. Spring Data MongoDB 一:入门篇(环境搭建、简单的CRUD操作)

    一.简介 Spring Data  MongoDB 项目提供与MongoDB文档数据库的集成.Spring Data MongoDB POJO的关键功能区域为中心的模型与MongoDB的DBColle ...

  2. spring data mongodb 配置遇到的几个问题

    一. mongodb 2.2版本以上的配置 spring.data.mongodb.uri = mongodb://newlook:newlook@192.168.0.109:27017/admin ...

  3. spring data mongodb中,如果对象中的属性不想加入到数据库字段中

    spring data mongodb中,如果对象中的属性不想加入到数据库字段中,可加@Transient注解,声明为透明属性 spring data mongodb 官网帮助文档 http://ww ...

  4. Spring Data MongoDB example with Spring MVC 3.2

    Spring Data MongoDB example with Spring MVC 3.2 Here is another example web application built with S ...

  5. 使用Spring访问Mongodb的方法大全——Spring Data MongoDB查询指南

    1.概述 Spring Data MongoDB 是Spring框架访问mongodb的神器,借助它可以非常方便的读写mongo库.本文介绍使用Spring Data MongoDB来访问mongod ...

  6. Spring data mongodb 聚合,投射,内嵌数组文档分页.

    尽量别直接用 DBObject  ,Spring data mongodb 的api 本来就没什么多大用处,如果还直接用 DBObject 那么还需要自己去解析结果,说动做个对象映射,累不累 Spri ...

  7. JAVA 处理 Spring data mongodb 时区问题

    Spring data mongodb 查询出结果的时候会自动 + 8小时,所以我们看起来结果是对的 但是我们查询的时候,并不会自动 + 8小时,需要自己处理 解决方法 1   @JsonFormat ...

  8. Spring data mongodb ObjectId ,根据id日期条件查询,省略@CreatedDate注解

    先看看ObjectId 的json 结构,非常丰富,这里有唯一机器码,日期,时间戳等等,所以强烈建议ID 使用 ObjectId 类型,并且自带索引 Spring data mongodb 注解 @C ...

  9. Spring data mongodb @CreatedBy@LastModifiedBy@CreatedBy@LastModifiedBy SpringSecurityAuditorAware,只记录用户名

    要在Spring data mongodb 中使用@CreatedBy@LastModifiedBy@CreatedBy@LastModifiedBy  这四个注解 必须实现 SpringSecuri ...

  10. Spring Data MongoDB 三:基本文档查询(Query、BasicQuery)(一)

    一.简单介绍 Spring Data  MongoDB提供了org.springframework.data.mongodb.core.MongoTemplate对MongoDB的CRUD的操作,上一 ...

随机推荐

  1. CSS选择器:#id和.class中间有空格和无空格的区别

    相信大家都知道 .class1 .class2 和 .class1.class2 是两种不同的选择规则,但具体怎样不同呢? 首先中间有空格的情况:是选择到.class1类下的.class2类子节点,即 ...

  2. ORA-16014: log 3 sequence# 540 not archived, no available destinations

    https://blog.csdn.net/zonelan/article/details/7329369

  3. Leetcode算法比赛----First Unique Character in a String

    问题描述 Given a string, find the first non-repeating character in it and return it's index. If it doesn ...

  4. Mybatis学习第三天——输入输出映射以及动态SQL

    注意:以下传入数据与输出数据类型部分使用别名的方式,别名在SqlMapConfig.xml核心文件中配置 1.输入映射 1.1 传递简单数据类型 1.2 传递pojo中的类类型 1.3 传递Query ...

  5. 用户登陆显示cpu、负载、内存信息

    #用户登陆显示cpu.负载.内存信息 #!/bin/bash # hostip=`ifconfig eth0 |awk -F" +|:" '/Bcast/{print $4}'` ...

  6. pmp证书

  7. Oracle spool 小结

    关于SPOOL(SPOOL是SQLPLUS的命令,不是SQL语法里面的东西.) 对于SPOOL数据的SQL,最好要自己定义格式,以方便程序直接导入,SQL语句如: select taskindex|| ...

  8. 【Oracle】DBMS_STATS.GATHER_TABLE_STATS详解

    由于Oracle的优化器是CBO,所以对象的统计数据对执行计划的生成至关重要!    作用:DBMS_STATS.GATHER_TABLE_STATS统计表,列,索引的统计信息(默认参数下是对表进行直 ...

  9. 加装固态硬盘SSD

    参考:http://tieba.baidu.com/p/4224078869 1.首先拆开后盖,取出机械硬盘,把固定框换到固态盘上,把机械盘安装到硬盘托架上. 装上固态硬盘,然后把光驱位的塑料壳子拆下 ...

  10. 使用信号进行同步 sem_post

    使用信号进行同步 信号是 E. W. Dijkstra 在二十世纪六十年代末设计的一种编程架构.Dijkstra 的模型与铁路操作有关:假设某段铁路是单线的,因此一次只允许一列火车通过. 信号将用于同 ...