Mongodb mapreduce java 操作

mongodb数据库中数据一览:

134500_epCK_2499632.png

有多条个cust_id数据,现统计cust_id为abc124用户items下sl为0.17和0.13分别的总和是多少

java代码如下:

MongoClient mongoClient = new MongoClient("192.168.1.45", 27017);
MongoCollection mongoCollection = mongoClient.getDatabase("tt").getCollection("tt");
String mapFunction = "function(){\n" +
        "for(var i = 0; i < this.items.length; i++){\n" +
        "var key = this.items[i].sl;\n" +
        "var value = {\n" +
        "count:1,\n" +
        "je: this.items[i].je,\n" +
        "se: this.items[i].se\n" +
        "};\n" +
        "emit(key, value);\n" +
        "}};\n";
String reduceFunction = "function(key,values){\n" +
        "reduceVal = {je:0,se:0};\n" +
        "for(var i = 0; i < values.length; i++){\n" +
        "reduceVal.je += values[i].je;\n" +
        "reduceVal.se += values[i].se;\n" +
        "}\n" +
        "return reduceVal;};\n";


JSONObject query = new JSONObject();
query.put("cust_id", "abc124");//设置查询条件
Document queryDoc = Document.parse(query.toString());
MapReduceIterable mri = mongoCollection.mapReduce(mapFunction, reduceFunction).filter(queryDoc);
MongoCursor mongoCursor = mri.iterator();
JSONArray jsonArray = new JSONArray();
while (mongoCursor.hasNext()){
    JSONObject object = JSON.parseObject(((Document) mongoCursor.next()).toJson().toString());
    JSONObject jsonObject = new JSONObject();
    String sl = object.getString("_id");
    object.put("sl", sl);
    object.remove("_id");
    jsonArray.add(object);
}
System.out.println(jsonArray);

想要的功能已经实现,旧版的mongodb的mapreduce方法如下:

DBObject query = new BasicDBObject();
query.put("cust_id", "abc124");
Mongo mongo = new Mongo("192.168.1.45", 27017);
DB db = mongo.getDB("tt");
DBCollection collection = db.getCollection("tt");
MapReduceCommand mapReduceCommand =
        new MapReduceCommand(collection, mapFunction, reduceFunction, null, MapReduceCommand.OutputType.INLINE, query);
MapReduceOutput mapReduceOutput = collection.mapReduce(mapReduceCommand);
JSONArray jsonArray = new JSONArray();
for (DBObject o : mapReduceOutput.results()) {
    JSONObject jsonObject = JSON.parseObject(o.toString());
    String sl = jsonObject.getString("_id");
    jsonObject.put("sl", sl);
    jsonObject.remove("_id");
    jsonArray.add(jsonObject);
}
System.out.println(jsonArray);

当然我们还是推荐使用新版,官网参考:https://docs.mongodb.com/manual/tutorial/map-reduce-examples/

 

 

 

 

 

 

转载于:https://my.oschina.net/u/2499632/blog/727752

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值