1. 程式人生 > >【MongoDB】java與MangoDB配合使用

【MongoDB】java與MangoDB配合使用

廢話不多說,我們先來引入需要使用的jar包


注意 MongoDB 不是隻引入mongodb-driver-3.4.1.jar  這個包就可以了  他還需要BSON的包和mongodb-driver-core-3.4.1.jar的包才可以 ,因為在使用java連線MongoDB時,如果不引入mongodb-driver-core-3.4.1.jar 這個會報如下錯誤


Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/connection/BufferProvider

然後按照下圖操作找到相關包下載地址

1.第一步 選擇你需要的版本 點選紅框處 Reference 


第二步,按照箭頭順序找到 installation頁面,拖動滾動條 找到bson 和 driver-core的包選擇相應的版本下載


當這三個包下載好就可以引入了

然後我粘上這邊的工具類的程式碼

親測是可以跑的

1.連線工具類

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

public class MongodbUtil {
	 static final String DBName = "test";
     static final String ServerAddress = "127.0.0.1"; 
     static final int PORT = 27017;


     public static MongoClient getMongoClient( ){
         MongoClient mongoClient = null;
         try {
               // 連線到 mongodb 服務
             mongoClient = new MongoClient(ServerAddress, PORT); 
             System.out.println("Connect to mongodb successfully");
         } catch (Exception e) {
             System.err.println(e.getClass().getName() + ": " + e.getMessage());
         }
         return mongoClient;
     }

     public static MongoDatabase getMongoDataBase(MongoClient mongoClient) {  
         MongoDatabase mongoDataBase = null;
         try {  
             if (mongoClient != null) {  
                   // 連線到資料庫
                 mongoDataBase = mongoClient.getDatabase(DBName);  
                 System.out.println("Connect to DataBase successfully");
             } else {  
                 throw new RuntimeException("MongoClient不能夠為空");  
             }  
         } catch (Exception e) {  
             e.printStackTrace();  
         }
         return mongoDataBase;
     }  

     public static void closeMongoClient(MongoDatabase mongoDataBase,MongoClient mongoClient ) {  
         if (mongoDataBase != null) {  
             mongoDataBase = null;  
         }  
         if (mongoClient != null) {  
             mongoClient.close();  
         }  
         System.out.println("CloseMongoClient successfully");  

     }  
}

2.幾個獲取MongoDB資料的方法,根據自己需要使用

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;

public class MongoDbUseUtil {
	public static Map<String, Integer> queryByID(MongoDatabase db, String table, Object Id) throws Exception {
		MongoCollection<Document> collection = db.getCollection(table);
		BasicDBObject query = new BasicDBObject("_id", Id);
		// DBObject介面和BasicDBObject物件:表示一個具體的記錄,BasicDBObject實現了DBObject,是key-value的資料結構,用起來和HashMap是基本一致的。
		FindIterable<Document> iterable = collection.find(query);
		Map<String, Integer> jsonStrToMap = null;
		MongoCursor<Document> cursor = iterable.iterator();
		while (cursor.hasNext()) {
			Document user = cursor.next();
			String jsonString = user.toJson();
			jsonStrToMap = jsonStrToMap(jsonString);
		}
		System.out.println("檢索ID完畢");

		return jsonStrToMap;
	}

	/**
	 * 根據一個doc,來檢索,當doc是空的時候檢索全部
	 * 
	 * @param db
	 * @param table
	 * @param doc
	 */
	public static List<Map<String, Integer>> queryByDoc(MongoDatabase db, String table, BasicDBObject doc) {
		MongoCollection<Document> collection = db.getCollection(table);
		FindIterable<Document> iterable = collection.find(doc);
		/**
		 * 1. 獲取迭代器FindIterable<Document> 2. 獲取遊標MongoCursor<Document> 3.
		 * 通過遊標遍歷檢索出的文件集合
		 */

		List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>();
		MongoCursor<Document> cursor = iterable.iterator();
		while (cursor.hasNext()) {
			Document user = cursor.next();
			String jsonString = user.toJson();
			Map<String, Integer> jsonStrToMap = jsonStrToMap(jsonString);
			list.add(jsonStrToMap);
		}
		System.out.println("檢索doc完畢");
		return list;
	}

	/**
	 * 檢索全部並返回迭代器
	 * 
	 * @param db
	 * @param table
	 */
	public static List<Map<String, Integer>> queryAll(MongoDatabase db, String table) {
		MongoCollection<Document> collection = db.getCollection(table);
		FindIterable<Document> iterable = collection.find();

		List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>();
		MongoCursor<Document> cursor = iterable.iterator();
		while (cursor.hasNext()) {
			Document user = cursor.next();
			String jsonString = user.toJson();
			Map<String, Integer> jsonStrToMap = jsonStrToMap(jsonString);
			list.add(jsonStrToMap);
		}
		System.out.println("檢索全部完畢");
		return list;
	}

	/**
	 * 便利迭代器FindIterable<Document>
	 */
	public static void printFindIterable(FindIterable<Document> iterable) {
		MongoCursor<Document> cursor = iterable.iterator();
		while (cursor.hasNext()) {
			Document user = cursor.next();
			System.out.println(user.toJson());
		}
		cursor.close();
	}
	/**
	 * 這個方法是貼上別人的
	 */
	public static Map<String, Integer> jsonStrToMap(String jsonString) {
        Object parseObj = JSON.parse(jsonString); // 反序列化 把json 轉化為物件
        Map<String, Integer> map = (HashMap<String, Integer>) parseObj; // 把物件轉化為map
        return map;
    }
}

然後附上測試方法

public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		MongoClient mongoClient = MongodbUtil.getMongoClient();
		MongoDatabase mongoDataBase = MongodbUtil.getMongoDataBase(mongoClient);
		List<Map<String, Integer>> queryAll = MongoDbUseUtil.queryAll(mongoDataBase, "myJava");
		System.out.println(queryAll);
	}