《MongoDB權威指南》學習整理----Java操作MongoDB實例

簡介

雖然上面我們介紹了很多MongoDB的知識,但是對於J2EE程序猿來說,我們最多的還是通過MongoDB的Driver來實現對MongoDB實例的操作,雖然我們在實際會遇到各種各種的MongoDB操作,但是都是較爲複雜的CRUD,所以我在這裏知識簡單的介紹下MongDB在Java中的使用,驅動的下載地址推薦使用maven連接OSChina的服務器下載,起碼我是這樣的,這裏我並沒有介紹太複雜的MongoDB實例的使用,主要是自己在實際工作中還沒有用到,以後使用中會更多的補充。好了,廢話已經說完,上代碼:

代碼

public class ChemSearch {

	public static void main(String[] args) {
		try {
			//創建MongoDB實例地址和端口集合
			List<ServerAddress> seeds = new ArrayList<ServerAddress>();
			seeds.add(new ServerAddress("localhost", 27017));
			//創建對應的驗證信息
			//MongoDB驗證在實例啓動時使用--auth
			List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
			credentialsList.add(MongoCredential.createMongoCRCredential("test1", "test", "ljcxlzbjwan".toCharArray()));
			//創建MongoDB實例客戶端連接
			MongoClient client = new MongoClient(seeds, credentialsList);
			//得到目標數據庫
			DB test = client.getDB("test");		
			//遍歷目標數據庫中的所有集合並答應
			for(String collectionName:test.getCollectionNames()){
				System.out.println(collectionName);
			}
			//創建並得到目標集合
			DBCollection collection = test.createCollection("javaTest", null);
			//創建一個Java對象
			Student student = new  Student();
			student.setAge(24);
			student.setName("李小呆");
			Grade grade = new Grade();
			grade.setName(3);
			grade.setTeacherName("李小呆");
			student.setGrade(grade);
			//插入數據到collection
			insertDocToCollection(student,collection);
			//查詢當前集合下的所有文檔
			DBCursor cursor= collection.find();
			printInter(cursor.iterator());
			Student student1 = new  Student();
			student1.setAge(27);
			student1.setName("李小呆1");
			student1.setGrade(grade);
			insertDocToCollection(student1, collection);
			cursor= collection.find();
			printInter(cursor.iterator());
			//根據條件查詢
			BasicDBObject query = new BasicDBObject();
			query.put("age", 27);
			DBObject new_info = collection.findOne(query);
			System.out.println(new_info);
			//更新數據
			BasicDBObject temp = new BasicDBObject();
			BasicDBObject temp1 = new BasicDBObject("age", 2);
			temp.put("$inc", temp1);
			collection.update(query, temp	);
			cursor= collection.find();
			printInter(cursor.iterator());
			//刪除數據
			collection.remove(query);
			cursor= collection.find();
			printInter(cursor.iterator());
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("rawtypes")
	private static void printInter(Iterator iterator){
		while(iterator.hasNext()){
			System.out.println(iterator.next());
		}
	}

	private static void insertDocToCollection(Object obj, DBCollection collection) {
		try {
			BasicDBObject stu1 = (BasicDBObject)objToDoc(obj);
			collection.insert(stu1);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	private static DBObject objToDoc(Object obj) throws IllegalArgumentException, IllegalAccessException {
		BasicDBObject basicDBObject = new BasicDBObject();
		Class cls = obj.getClass();
		for(Field field : cls.getDeclaredFields()){
			field.setAccessible(true);
			if(field.getType().getPackage().getName().startsWith("java.lang")){
				basicDBObject.put(field.getName(), field.get(obj));
			}else{
				basicDBObject.put(field.getName(), objToDoc(field.get(obj)));
			}
		}
		return basicDBObject;
	}
}

簡單說明

通過上面的代碼我們可以簡單的看出來,MongoDB中文檔的概念都是由JAVA中的DBObject接口來抽象化的,而我們常用的是BasicDBObject類。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章