今天接到一个任务,统计一张mongo中询价表中的数据,字段有cityName,cityId,calDate,updateDate,price,amountOfIncrease.
这张表是每隔一段时间生成数据,所有会存在cityId相同而calDate不同的情况,现在要查出calDate离现在最近的每个城市的数据,也就是说要按城市分组,查出每个城市中calDate最大的数据.
最开始我想的是用聚合操作分组查出每个城市的calDate最大值,后来发现聚合的分组不能将除了分组的key(也就是分组字段)的其他字段查出来.在网上查了很多资料,都没有用spring template实现的,后来看到mongo查询语法中有个first,也就是可以只取第一条,如果分组也能取第一条,那么利用排序,问题就解决了.
看了下API,果然有first,不过是每个需要的字段都需要用first
List<AggregationOperation> operations = new ArrayList<>();
operations.add(Aggregation.match(Criteria.where("cityId").in(ids)));
operations.add(Aggregation.group("cityId")
.max("calDate").as("calDate").first("cityName").as("cityName")
.first("updateDate").as("updateDate").first("price").as("price").first("amountOfIncrease").as("amountOfIncrease")
);
operations.add(Aggregation.sort(Sort.Direction.DESC, "calDate"));
Aggregation aggregation = Aggregation.newAggregation(operations);
AggregationResults<BasicDBObject> g = mongoDdlpdbTemplate.aggregate(aggregation, CityPrice.class, BasicDBObject.class);
问题解决