1,实现一个
GroupOperation groupOperation = Aggregation.group("stockno").max("volume").as("volume");
Aggregation agg = Aggregation.newAggregation(StockQuotation.class,groupOperation); AggregationResults<java.util.Map> results = mongoTemplate.aggregate(agg,StockQuotation.class,java.util.Map.class); java.util.Map<String, Integer> classMaxScoreMap = new HashMap<String, Integer>(); if(results.getMappedResults() != null && results.getMappedResults().size() != 0){ for(java.util.Map map:results.getMappedResults()){ classMaxScoreMap.put(map.get("_id").toString(), Integer.valueOf(map.get("volume").toString())); System.out.println("==============" + map.get("_id").toString() + " | " + Integer.valueOf(map.get("volume").toString())); } }
打印结果:
==============600004 | 6465485
==============600000 | 74449284因为Aggregation.group()函数,参数不能为空,所以必须要分组,如果查询整个表里面某个列的最大值,这办法不行
2,写个日期的
//stockno,tradingDay是实体类中的字段,maxTradingDay是别名
GroupOperation groupOperation = Aggregation.group("stockno").max("tradingDay").as("maxTradingDay"); Aggregation agg = Aggregation.newAggregation(StockQuotation.class,groupOperation); AggregationResults<java.util.Map> results = mongoTemplate.aggregate(agg,StockQuotation.class,java.util.Map.class); java.util.Map<String, Object> classMaxScoreMap = new HashMap<String, Object>(); if(results.getMappedResults() != null && results.getMappedResults().size() != 0){ for(java.util.Map map:results.getMappedResults()){ classMaxScoreMap.put(map.get("_id").toString(), map.get("maxTradingDay").toString()); System.out.println("==============" + map.get("_id").toString() + " | " + map.get("maxTradingDay").toString()); } }打印结果:
==============600004 | Mon May 12 00:00:00 CST 2008
==============600000 | Mon May 12 00:00:00 CST 2008