springmvc+mongodb中group方法的書寫
阿新 • • 發佈:2019-01-27
因為資料量增大的問題,現在越來越多的猿們開始使用mongodb等的nosql資料庫了。不過mongodb非關係型,查詢時還是有些許的不便的,比如我們在mysql等裡面使用的聚合,在mongodb中就不太一樣。
mongodb中的語句不一樣,我們java中呼叫就更不一樣了。先看一段程式碼:
這個是查詢每個word中數值最大的price1。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; }
和它對應的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值也會對應不上!!!