public List<PlaybackEntity> queryPlaybackRecord(FunctionUseQueryEntity queryEntity){
Criteria criteria = Criteria.where("createTime").gte(queryEntity.getStartTime()).lte(queryEntity.getEndTime())
.and("status").is(1);
Query query = Query.query(criteria);
BasicDBObject initial = new BasicDBObject();
initial.put("playbackNum", 0);
String reduce = getReduce();
//进行按天、周、月分组
String keyf = getKeyf(queryEntity);
DBCollection collection = mongoTemplate.getCollection(COLLNAME);
GroupCommand xx = new GroupCommand(collection, keyf, query.getQueryObject(), initial, reduce, null);
BasicDBList objects = (BasicDBList)collection.group(xx);
List<PlaybackEntity> results = new ArrayList<PlaybackEntity>();
if (objects != null) {
for (int i = 0; i < objects.size(); i++) {
PlaybackEntity play = new PlaybackEntity();
DBObject obj = (DBObject) objects.get(i);
play.setFormateTime((String)obj.get("strData"));
play.setPlaybackNum((Double)obj.get("playbackNum"));
results.add(play);
}
}
return results;
}
private String getKeyf(FunctionUseQueryEntity queryEntity) {
StringBuilder keyfBuilder = new StringBuilder();
keyfBuilder.append("function(doc){ ")
.append(" var date = new Date(doc.createTime); ");
if(DateType.DATE.getValue().equals(queryEntity.getType())){
keyfBuilder.append(" var dateKey = '' + date.getFullYear()+ '-' + (date.getMonth()+1) + '-' + date.getDate();");
}else if(DateType.WEEK.getValue().equals(queryEntity.getType())){
keyfBuilder.append(" var firstDay = new Date(date.getFullYear(),0, 1);")
.append(" var dayOfWeek = firstDay.getDay();")
.append(" var spendDay= 1;")
.append(" if (dayOfWeek !=0) {")
.append(" spendDay= 7 - dayOfWeek + 1;")
.append(" }")
.append(" firstDay = new Date(date.getFullYear(), 0, 1 + spendDay);")
.append(" var d =Math.ceil((date.valueOf()- firstDay.valueOf())/ 86400000);")
.append(" var week =Math.ceil(d/7);")
.append(" week = week + 1;");
keyfBuilder.append(" var dateKey = '' + date.getFullYear()+ '-' + week;");
}else if(DateType.MONTH.getValue().equals(queryEntity.getType())){
keyfBuilder.append(" var dateKey = '' + date.getFullYear()+ '-' + (date.getMonth()+1);");
}
keyfBuilder.append(" return {'strData':dateKey}; ")
.append(" }");
return keyfBuilder.toString();
}
private String getReduce() {
StringBuilder reduceBuilder = new StringBuilder();
reduceBuilder.append("function Reduce(doc, out) { ")
.append(" out.playbackNum += 1; ")
.append(" }");
return reduceBuilder.toString();
}
java操作 mongodb 进行 按天、周、月分组统计
点赞
收藏