Java語言標準的數據庫時MySQL,可是有些時候也會用到MongoDB,此次Boss交代處理MongoDB,因此講代碼以及思路記錄下了html
摸索的過程,才發現軟件的適用仍是很重要的啊!!!java
我鏈接的MongoDB的數據是遠程數據庫,鏈接本地數據庫的方法網上有不少:mongodb
//鏈接到MongoDB服務 若是是遠程鏈接能夠替換「localhost」爲服務器所在IP地址 //ServerAddress()兩個參數分別爲 服務器地址 和 端口 ServerAddress serverAddress = new ServerAddress("106.12.34.175",27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三個參數分別爲 用戶名 數據庫名稱 密碼 MongoCredential credential = MongoCredential.createScramSha1Credential("***", "***", "***".toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //經過鏈接認證獲取MongoDB鏈接 MongoClient mongoClient = new MongoClient(addrs,credentials); //鏈接到數據庫 MongoDatabase mongoDatabase = mongoClient.getDatabase("***"); MongoCollection<Document> collection = mongoDatabase.getCollection("dianping_city"); //查詢過程 BasicDBObject query = new BasicDBObject(); query.put("city_num","xxx"); //查詢結果 //MongoCursor<Document> cursor = collection.find(query).skip(0).limit(10).iterator(); MongoCursor<Document> cursor = collection.find(query).skip(0).iterator();
這樣查詢結果就有了,下面要將查詢結果存儲爲CSV文件,我這裏實現的是對查詢的結果進行存儲(對於多條的查詢數據,也一併放入CSV文件中);存儲的過程須要注意:從MongoDB返回的數據類型,多條數據類型在CSV文件中的對齊。數據庫
List<String> resultList = new LinkedList<>(); List<String> tableList = new ArrayList<>(); while (cursor.hasNext()) { String jsonString = new String(); jsonString = cursor.next().toJson(); int length = jsonString.length(); jsonString = "[{" + jsonString.substring(jsonString.indexOf(",") + 1, length) + "]"; System.out.println(jsonString); JSONArray jsonArray = new JSONArray(jsonString); JSONObject jsonObject = jsonArray.getJSONObject(0); try { if(tableList.size() == 0) { StringBuilder stringKey = new StringBuilder(); Iterator iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = (String) iterator.next(); if(key.compareTo("shophours") == 0){continue;} tableList.add(key); stringKey.append(key).append(','); } resultList.add(stringKey.deleteCharAt(stringKey.length()-1).toString()); } StringBuilder stringValue = new StringBuilder(); for(String entry: tableList){ String value = new String(); if(!jsonObject.has(entry)){ value = "null"; } else { value = jsonObject.get(entry).toString(); } stringValue.append(value).append(','); } resultList.add(stringValue.deleteCharAt(stringValue.length()-1).toString()); } catch (JSONException e){ e.printStackTrace(); } }
總結一下:以前沒有處理過MongoDB,因此在這個small task上花了點時間,不過最後也有收穫,至少MongoDB與Java相關的坑踩了一部分,爲之後積累經驗嘛。json
總體代碼:服務器
1 package MongoDB; 2 3 import com.mongodb.*; 4 import com.mongodb.client.MongoCollection; 5 import com.mongodb.client.MongoCursor; 6 import com.mongodb.client.MongoDatabase; 7 import org.bson.Document; 8 import org.json.*; 9 import java.io.*; 10 import java.util.*; 11 12 public class outputData { 13 public static void main(String[] args){ 14 //鏈接到MongoDB服務 若是是遠程鏈接能夠替換「localhost」爲服務器所在IP地址 15 //ServerAddress()兩個參數分別爲 服務器地址 和 端口 16 ServerAddress serverAddress = new ServerAddress("IP",port); 17 List<ServerAddress> addrs = new ArrayList<ServerAddress>(); 18 addrs.add(serverAddress); 19 20 //MongoCredential.createScramSha1Credential()三個參數分別爲 用戶名 數據庫名稱 密碼 21 MongoCredential credential = MongoCredential.createScramSha1Credential("***", "***", "***".toCharArray()); 22 List<MongoCredential> credentials = new ArrayList<MongoCredential>(); 23 credentials.add(credential); 24 25 //經過鏈接認證獲取MongoDB鏈接 26 MongoClient mongoClient = new MongoClient(addrs,credentials); 27 28 //鏈接到數據庫 29 MongoDatabase mongoDatabase = mongoClient.getDatabase("****"); 30 MongoCollection<Document> collection = mongoDatabase.getCollection("dianping_city"); 31 32 //查詢過程 33 BasicDBObject query = new BasicDBObject(); 34 query.put("city_num","xxx"); 35 36 //查詢結果 37 //MongoCursor<Document> cursor = collection.find(query).skip(0).limit(10).iterator(); 38 MongoCursor<Document> cursor = collection.find(query).skip(0).iterator(); 39 40 41 List<String> resultList = new LinkedList<>(); 42 List<String> tableList = new ArrayList<>(); 43 while (cursor.hasNext()) { 44 String jsonString = new String(); 45 jsonString = cursor.next().toJson(); 46 int length = jsonString.length(); 47 jsonString = "[{" + jsonString.substring(jsonString.indexOf(",") + 1, length) + "]"; 48 System.out.println(jsonString); 49 50 JSONArray jsonArray = new JSONArray(jsonString); 51 JSONObject jsonObject = jsonArray.getJSONObject(0); 52 try { 53 if(tableList.size() == 0) { 54 StringBuilder stringKey = new StringBuilder(); 55 Iterator iterator = jsonObject.keys(); 56 while (iterator.hasNext()) { 57 String key = (String) iterator.next(); 58 if(key.compareTo("shophours") == 0){continue;} 59 tableList.add(key); 60 stringKey.append(key).append(','); 61 } 62 resultList.add(stringKey.deleteCharAt(stringKey.length()-1).toString()); 63 } 64 StringBuilder stringValue = new StringBuilder(); 65 for(String entry: tableList){ 66 String value = new String(); 67 if(!jsonObject.has(entry)){ 68 value = "null"; 69 } 70 else { 71 value = jsonObject.get(entry).toString(); 72 } 73 stringValue.append(value).append(','); 74 } 75 resultList.add(stringValue.deleteCharAt(stringValue.length()-1).toString()); 76 } 77 catch (JSONException e){ 78 e.printStackTrace(); 79 } 80 } 81 cursor.close(); 82 83 try { 84 File csv = new File("C:\\Users\\Administrator\\Desktop\\tmp2.csv"); 85 OutputStreamWriter outStream = null; 86 outStream = new OutputStreamWriter(new FileOutputStream(csv), "GBK"); 87 BufferedWriter bw = new BufferedWriter(outStream); 88 for(String entry : resultList){ 89 // 添加新的數據行 90 bw.write(entry.toCharArray()); 91 bw.newLine(); 92 } 93 bw.close(); 94 } 95 catch (FileNotFoundException e) { 96 // File對象的建立過程當中的異常捕獲 97 e.printStackTrace(); 98 } catch (IOException e) { 99 // BufferedWriter在關閉對象捕捉異常 100 e.printStackTrace(); 101 } 102 System.out.println("MongoDB connect successfully: "+"mongoDatabase = " + mongoDatabase.getName()); 103 } 104 }
最後貼上幾個爲之後作準備的連接:app
MongoDB安裝:http://www.cnblogs.com/lzrabbit/p/3682510.htmlide
Java下MongoDB查詢:https://www.cnblogs.com/luoaz/p/4691639.htmlui