mongodb數據庫中數據一覽:java
有多條個cust_id數據,現統計cust_id爲abc124用戶items下sl爲0.17和0.13分別的總和是多少mongodb
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方法以下:json
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/this