Java對MongoDB中的數據查詢處理


Java語言標准的數據庫時MySQL,但是有些時候也會用到MongoDB,這次Boss交代處理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相關的坑踩了一部分,為以后積累經驗嘛。

整體代碼:

  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 }
View Code

 

最后貼上幾個為以后做准備的鏈接:

MongoDB安裝:http://www.cnblogs.com/lzrabbit/p/3682510.html

Java下MongoDB查詢:https://www.cnblogs.com/luoaz/p/4691639.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM