java group 查询 MongoDB 使用keyf

来源:互联网 发布:网络被劫持怎么处理 编辑:程序博客网 时间:2024/05/22 01:45

需求是查询xxx时间段服务器处理xxxxapi时的耗时, 即 sum(finish - recieve)

背景:mongodb  3.2.6 , 数据库下有名为 log的collection  

字段如下 

{    "_id" : ObjectId("12312"),    "api" : "/search",    "devId" : "xxxx",    "appId" : "1",    "recieve" : ISODate("2016-09-06T17:53:05.718Z"),    "finish" : ISODate("2016-09-06T17:53:05.718Z"),}

查询的数据是:分组按照 finTime 取年月日时、api。

统计的是: 计算数据 【finTime -  reqTime】 值  和  【数据条数】


写的mongo语句如下

db.log.group({  keyf : function(doc){   var date = new Date(doc.recieve.getTime() - 8 * 60 * 60 * 1000 );   //牵涉到时区, 时间统一减去 8小时   var dateKey = '' + date.getFullYear()+ '-' + (date.getMonth()+1) + '-' + date.getDate() + ' ' + (date.getHours());   return {'day':dateKey, 'api' : doc.api}; //33 },  initial : {'count':0, 'acceptTime' : 0},  reduce : function Reduce(doc, out) {  if(doc.reqTime){    out.count +=1;    out.acceptTime += new Date(doc.finish).getTime() - new Date(doc.recieve).getTime();  } }, condition:{recieve:{$gt: ISODate('2016-09-06T01:44:43.703Z')}, devId : 'xxx' }});

Java语句

<pre name="code" class="java">  Query <span style="background-color: rgb(51, 204, 255);">query </span>= Query.query(Criteria.where("devId").is("xxx"));  BasicDBObject <span style="background-color: rgb(51, 204, 255);">initial </span>= new BasicDBObject();  initial.put("count", 0);  initial.put("acceptTime", 0);  String <span style="background-color: rgb(51, 204, 255);">reduce </span>= "function Reduce(doc, out) { " +"   if(doc.reqTime){ " +"     out.count +=1; " +"     out.acceptTime += new Date(doc.finTime).getTime() - new Date(doc.reqTime).getTime(); " +"   } " +" }";  String <span style="background-color: rgb(51, 204, 255);">keyf </span>= "function(doc){ " +"   var date = new Date(doc.reqTime ); " +"   var dateKey = '' + date.getFullYear()+ '-' + (date.getMonth()+1) + '-' + date.getDate() + ' ' + (date.getHours()-8); " +"   return {'day':dateKey, 'api' : doc.api};  " +" }";  DBCollection <span style="background-color: rgb(51, 204, 255);">collection </span>= mongoTemplate.getCollection("log");  GroupCommand xx = new GroupCommand(<span style="background-color: rgb(255, 255, 51);">collection</span>, <span style="background-color: rgb(255, 255, 51);">keyf</span>, <span style="background-color: rgb(255, 255, 51);">query</span>.getQueryObject(), <span style="background-color: rgb(255, 255, 51);">initial</span>, <span style="background-color: rgb(255, 255, 51);">reduce</span>, null);  DBObject  object =  <span style="color:#ff0000;">mongoTemplate.getCollection("log").group(xx);</span>  Map<String , Object> map = object.toMap();



蓝色是参数定义


不理解的,代码中GroupCommand中既然传递 collection了,为什么group(...)只有在DBCollection中才有。 没必要设置两次collection。 有明白的大神请点明。





1 0