(以userId分组,统计用户数量,累加amout字段值,取amout字段最大值)
DBObject group = (DBObject) JSON.parse("{$group:{_id:'$userId', count:{$sum:1},total:{$sum:'$amount'},maxSigle:{$max:'$amount'}}}");
条件拼接完,开始查询:
List<DBObject> list = new ArrayList<DBObject>(); list.add(match); list.add(group); AggregationOutput Output = mongoTemplate.getCollection("表名").aggregate(list);
遍历结果就不用在说了。上面已经详细描述了
第二种方法是不是比一种方式简单多了。但是比较考验自身对mongodb语句熟悉性。
【扩展】
接着上面的方法进行扩展
//status 为0或者为1 ; type 不为11;time在beginDay ~ endDay时间段内 DBObject match = (DBObject) JSON.parse("{$match:{'status':{$in:['0','1']}, type:{$ne:11},'time':{$gte:'"+beginDay+"',$lte:'"+endDay+"'}}}"); //以用户Id分组,统计查询次数,取最后一次time的时间 DBObject group = (DBObject) JSON.parse("{$group:{_id:'$userId', count:{$sum:1},lastTime:{$max:'$time'} }}"); //在上一步统计出的结果中筛选次数大于100的数据 DBObject groupMatch = (DBObject) JSON.parse("{$match:{count:{$gte:100}}}"); //$project----查询结果中需要显示哪些字段,显示则设置为1。如下需要不显示_id 域(字段),则需如下指定: //db.集合名.aggregate( [ { $project : { _id: 0, count: 1 , lastSuccTime: 1 } } ] ) DBObject project = (DBObject) JSON.parse("{$project:{_id:1,count:1,lastSuccTime:1}}"); DBObject sort = (DBObject) JSON.parse("{$sort:{'count':-1}}");//排序 List<DBObject> list = new ArrayList<DBObject>(); list.add(match); list.add(group); list.add(groupMatch); list.add(project); list.add(sort); AggregationOutput catchOutPut = mongoTemplate.getCollection("表名") .aggregate(list);//查询结果
三、BasicDBObject+脚本语句
BasicDBObject groupIndex = new BasicDBObject(); BasicDBObject distinctQuery = new BasicDBObject(); distinctQuery.put("userId", new BasicDBObject("$in", userIds));//UserIds数组 BasicDBObject initIndex = new BasicDBObject(); initIndex.put("count", 0);//给count赋初值 // 脚本(doc代表数据库的数据.prev代表查询结果//prev.count这里的count就是上一步initIndex的count) String reduce = "function(doc, prev) {if(doc.status==0){prev.count+= 1;};}"; List<Map<String, Object>> basicDBList = (List<Map<String, Object>>) mongoTemplate. getCollection("Collection").group(groupIndex, distinctQuery, initIndex, reduce, null);
最后循环遍历List即可得到结果【PS:group这种聚合方式有个限制条件--->超过20000数据就会报错】
以上就是我在普通业务处理中用到mongodb聚合处理。如果有更好的方法或是有需要改进的地方,欢迎大家给我留言~