1、数据准备
db.sell.insert({"price":8.0,"amount":500.0,"status":"a"}) db.sell.insert({"price":8.0,"amount":450.0,"status":"a"}) db.sell.insert({"price":8.0,"amount":400.0,"status":"a"}) db.sell.insert({"price":9.0,"amount":350.0,"status":"a"}) db.sell.insert({"price":9.0,"amount":300.0,"status":"a"}) db.sell.insert({"price":9.0,"amount":250.0,"status":"a"}) db.sell.insert({"price":9.0,"amount":200.0,"status":"a"}) db.sell.insert({"price":10.0,"amount":150.0,"status":"d"}) db.sell.insert({"price":10.0,"amount":100.0,"status":"d"}) db.sell.insert({"price":10.0,"amount":50.0,"status":"d"}) db.sell.insert({"price":10.0,"amount":0.0,"status":"d"})
2、MapReduce
private static void testMapReduce3x() { MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase db = mongoClient.getDatabase("test"); MongoCollection collection = db.getCollection("sell"); String map = "function(){emit(this.price,this.amount);}"; String reduce = "function(key, values){return Array.sum(values)}"; MapReduceIterable out = collection.mapReduce(map, reduce); MongoCursor cursor = out.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } private static void testMapReduce2x() { MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase db = mongoClient.getDatabase("test"); BasicDBObject query=new BasicDBObject("status","a"); DBCollection dbcollection = mongoClient.getDB("test").getCollection("sell"); String map = "function(){emit(this.price,this.amount);}"; String reduce = "function(key, values){return Array.sum(values)}"; MapReduceCommand cmd = new MapReduceCommand(dbcollection, map, reduce, "outputCollection", MapReduceCommand.OutputType.INLINE, query); MapReduceOutput out2 = dbcollection.mapReduce(cmd); for (DBObject o : out2.results()) { System.out.println(o.toString()); } }