1 package com.sy.demo; 2 3 import com.mongodb.MongoClient; 4 5 import com.mongodb.client.FindIterable; 6 import com.mongodb.client.MapReduceIterable; 7 import com.mongodb.client.MongoCollection; 8 import com.mongodb.client.MongoCursor; 9 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 13 import java.io.File; 14 import java.io.FileOutputStream; 16 import java.text.SimpleDateFormat; 18 import java.util.Calendar; 19 import java.util.Date; 21 22 public class MongoDBJDBC2 { 23 public static void main(String[] args) { 24 try { 25 MongoClient mongoClient = new MongoClient("localhost", 27017); 26 MongoDatabase db = mongoClient.getDatabase("data"); 27 MongoCollection<Document> coll = db.getCollection("factPunishment"); 28 Calendar cal = Calendar.getInstance(); 29 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 30 cal.add(Calendar.MONTH, -6); 32 String compareDate = format.format(cal.getTime()); 33 String currentDate = format.format(Calendar.getInstance().getTime()); 34 String mapFunc = "function(){" + "if(this.factName=='诈骗数额特别巨大'){" + 35 "if(this.createDate<='" + currentDate + 36 "' && this.createDate>='" + compareDate + "'){" + 37 "emit(this.factPunishment, 1);" + "}" + "};" + "}"; 38 String reduceFunc = "function( key, values ){ return Array.sum(values); }"; 39 MapReduceIterable<Document> result = coll.mapReduce(mapFunc,reduceFunc); 41 String str = ""; 42 43 for (Document d : result) { 44 str += ("起刑点:" + d.get("_id") + ",案件量:" + d.get("value") + " "); 46 System.out.println("起刑点:" + d.get("_id") + ",案件量:" + d.get("value")); 48 } 49 50 FileOutputStream out = new FileOutputStream(new File("D://test//factPunishment.txt")); 52 out.write(str.getBytes()); 53 out.close(); 54 } catch (Exception e) { 55 System.err.println(e.getClass().getName() + ": " + e.getMessage()); 56 } 57 } 58 }