java实现mongodb的map-reduce过程

String map = "function () {" 
+   " var key = this.custNo; "
+   " var value = {custNo: this.custNo,loanNo:this.loanNo,"

+   "              list:[{"
+   "                  certNo:this.list.certNo,"
+   "                  phoneNo:this.list.phoneNo,"
+   "                  phoneName:this.list.phoneName,"
+   "                  othMsg:this.list.othMsg"
+   "                  }]"
+   "              };"
+   "    emit(key, value);"
+ "}";



// reduce 函数
String reduce = "function(key, values) {"
+ " var result = {custNo:key,loanNo:null,list:[]};"
+ " values.forEach( function(value) {"
+ " result.list = result.list.concat(value.list);"
+ "     });"
+ " result.loanNo = values[0].loanNo;"
+ " return result;"
+ "}";



BasicDBObject query = new BasicDBObject();

MapReduceCommand cmd = new MapReduceCommand(calllists, map, reduce,
"out_user", MapReduceCommand.OutputType.REPLACE, query);// out_user是指定的输出数据的集合
MapReduceOutput out = calllists.mapReduce(cmd);

Object [] str_array = null;  //通过数组读取jsonstr
String jsonStr = null;     //保存最终得到的json格式

for (DBObject o : out.results()) {
str_array = o.toMap().values().toArray();
jsonStr = str_array[1].toString();
}

最后得到的JSON格式如下:

{
 "custNo": "456654",
   "loanNo": "654321",
   "list": [
    {
      "certNo": "130406199302073017",
      "phoneNo": "18583738107",
      "phoneName": "duxin",
      "othMsg":"jjj"
    },
    {
      "certNo": "654321",
      "phoneNo": "13256565544",
      "phoneName": "haha",
      "othMsg":"hahaha"
    }
  ]
}


————————————————
版权声明:本文为CSDN博主「艾慕达」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/a18716374124/article/details/74101187

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值