因为数据量增大的问题,现在越来越多的猿们开始使用mongodb等的nosql数据库了。不过mongodb非关系型,查询时还是有些许的不便的,比如我们在mysql等里面使用的聚合,在mongodb中就不太一样。
mongodb中的语句不一样,我们java中调用就更不一样了。先看一段代码:
public Map<String, Object> queryUserMaxPrice(String userId) {
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(Criteria.where("userId").is(userId)),
Aggregation.group("word").max("price1").as("maxPrice"),
Aggregation.project("maxPrice").and("word").previousOperation()
);
AggregationResults groupResults = mongoTemplate.aggregate(agg, DayWordPrice.class, Map.class);
Map<String, Object> resultMap = new HashMap<String, Object>();
List<Map> mappedResults = groupResults.getMappedResults();
for (Map mappedResult : mappedResults) {
if (mappedResult.get("word") != null)
resultMap.put(mappedResult.get("word").toString(), mappedResult.get("maxPrice"));
}
return resultMap;
}
这个是查询每个word中数值最大的price1。
和它对应的sql语句应该是:select max(price1) as maxPrice,word from dayWordPrice where userId = #{userId} group by word
但是这里面需要注意的一点是:Aggregation.project 里面是写你需要输出的属性,and里面写group的属性,然后后面的previousOperation则是为了在输出时将word在map中的key值设置为word,如果没有这个,那么输出的map中,group的属性会默认输出为“_id”,也就是当成主键,这个是需要强调的,然后project和and里面的属性不能换位置,换了位置,属性就会丢失,而且key值也会对应不上!!!