mongodb的分組排序取第一條
阿新 • • 發佈:2019-02-06
mongotemplate的mapreduce方法
reduce的處理條數超過100時會用兩個reduce處理 第二次調reduce函式時 fixCardValue和chargeDate會重新初始化 然後拋異常
//根據car_no分組,charge_date時間排序,取最近一條記錄的fix_card_value Criteria criteria = Criteria.where("project_id").is(project_id); Query query = new Query(criteria); String map = "function(){" + "emit(" + "this.car_no," + "{fixCardValue:this.fix_card_value,chargeDate:this.charge_date}" + ");" + "}"; String reducef = "function(key,values){" + "var fixCardValue = values[0].fixCardValue;" + "var chargeDate = values[0].chargeDate;"+ "for(var i=1;i<values.length;i++){" + "if(values[i].chargeDate>chargeDate){" + "fixCardValue = values[i].fixCardValue};" + "} " + "return fixCardValue;}"; MapReduceResults<BasicDBObject> mapReduceResults = mongoTemplate.mapReduce(query, "charge_data", map, reducef, BasicDBObject.class); Iterator iterator = mapReduceResults.iterator(); while (iterator.hasNext()) { String jsonString = iterator.next().toString(); JSONObject jsonObject = JSONObject.parseObject(jsonString); String key = jsonObject.getString("_id"); int value = jsonObject.getJSONObject("value").getDouble("fixCardValue").intValue(); }
reduce的處理條數超過100時會用兩個reduce處理 第二次調reduce函式時 fixCardValue和chargeDate會重新初始化 然後拋異常
將reduce函式改下如下方式:
String reducef = "function(key,values){" + "var fixCardValue = 999;" + "var chargeDate = '1970-01-01';" + "for(var i=0;i<values.length;i++){" + "if(values[i].chargeDate>chargeDate){" + "fixCardValue = values[i].fixCardValue};" + "} " + "return fixCardValue;}";