mongdb 데이터베이스 기본 조작


	/**
	 *  DB 
	 */
	public static void addDBObject(DBCollection collection,BasicDBObject object){
		collection.insert(object);
	}
	
	/**
	 *  id DBObject
	 */
	public static DBObject getDBObjectById(String value) throws UnknownHostException, MongoException{
		dbc = getDBCollection("company", "users").find(new BasicDBObject("_id",new ObjectId(value)));
		DBObject ob = null;
		int i = 0;
		while(dbc.hasNext()){
			ob = dbc.next();
			i++;
		}
		if(i == 1){
			return ob;
		}else{
			return null;
		}
	}
	
	/**
	 *  key value 
	 */
	public static DBObject getDBObject(String key,String value) throws UnknownHostException, MongoException{
		dbc = getDBCollection("company", "users").find(new BasicDBObject(key,value));
		DBObject ob = null;
		int i = 0;
		while(dbc.hasNext()){
			ob = dbc.next();
			i++;
		}
		if(i == 1){
			return ob;
		}else{
			return null;
		}
	}
	
	/**
	 *  ( ) ( )
	 */
	public static Set<String> getCollectionsNames(String DBName) throws MongoException, UnknownHostException{
		return getDB(DBName).getCollectionNames();
	}
	
	/**
	 *  db ( )
	 */
	public static Set<DBObject> getDBObjects(DBCollection collection){
		Set<DBObject> dbObjects = new HashSet<DBObject>();
		DBCursor cursor = collection.find();
		while(cursor.hasNext()){
			DBObject object = cursor.next();
			dbObjects.add(object);
		}
		return dbObjects;
	}
	
	/**
	 *  / ( )
	 */
	public static DBCollection getDBCollection(String DBName,String collectionName) throws UnknownHostException, MongoException{
		return getDB(DBName).getCollection(collectionName);
	}
	
	/**
	 *  / 
	 */
	public static DB getDB(String DBName) throws UnknownHostException, MongoException{
		return getMongo().getDB(DBName);
	}
	
	/**
	 *  
	 */
	public static Mongo getMongo() throws UnknownHostException, MongoException{
		Mongo mg = null;
		if(mg == null){
			mg = new Mongo();
		}
		return mg;
	}
	
	/**
	 *  
	 */
	public static void destory(Mongo mg) {
		if (mg != null){
			mg.close();
			mg = null; 
		}
		System.gc();    
	}
	
	/**
	 *  
	 */
	public static List<String> getDBNames() throws MongoException, UnknownHostException{
		return getMongo().getDatabaseNames();
	}
	
	/**
	 *  
	 */
	public static void deleteDB(String DBName) throws MongoException, UnknownHostException{
		getMongo().dropDatabase(DBName);
	}

좋은 웹페이지 즐겨찾기