因爲數據量增大的問題,現在越來越多的猿們開始使用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值也會對應不上!!!