mongodb的分组排序取第一条

    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;ichargeDate){" +
        "fixCardValue = values[i].fixCardValue};" +
        "} " +
        "return fixCardValue;}";
MapReduceResults 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;ichargeDate){" +
        "fixCardValue = values[i].fixCardValue};" +
        "} " +
        "return fixCardValue;}";

你可能感兴趣的:(mongo)