/**
* 插入一條DB對象
*/
public static void addDBObject(DBCollection collection,BasicDBObject object){
collection.insert(object);
}
/**
* 根據(jù)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;
}
}
/**
* 根據(jù)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;
}
}
/**
* 根據(jù)數(shù)據(jù)庫名獲取(新增)下面所有聚集名(表名)
*/
public static SetString> getCollectionsNames(String DBName) throws MongoException, UnknownHostException{
return getDB(DBName).getCollectionNames();
}
/**
* 遍歷聚集中的db對象集合(相當(dāng)于關(guān)系數(shù)據(jù)庫中的數(shù)據(jù))
*/
public static SetDBObject> getDBObjects(DBCollection collection){
SetDBObject> dbObjects = new HashSetDBObject>();
DBCursor cursor = collection.find();
while(cursor.hasNext()){
DBObject object = cursor.next();
dbObjects.add(object);
}
return dbObjects;
}
/**
* 獲取/新增聚集(相當(dāng)于關(guān)系數(shù)據(jù)庫表)
*/
public static DBCollection getDBCollection(String DBName,String collectionName) throws UnknownHostException, MongoException{
return getDB(DBName).getCollection(collectionName);
}
/**
* 獲取/新增數(shù)據(jù)庫
*/
public static DB getDB(String DBName) throws UnknownHostException, MongoException{
return getMongo().getDB(DBName);
}
/**
* 連接數(shù)據(jù)庫
*/
public static Mongo getMongo() throws UnknownHostException, MongoException{
Mongo mg = null;
if(mg == null){
mg = new Mongo();
}
return mg;
}
/**
* 關(guān)閉連接
*/
public static void destory(Mongo mg) {
if (mg != null){
mg.close();
mg = null;
}
System.gc();
}
/**
* 獲取數(shù)據(jù)庫名
*/
public static ListString> getDBNames() throws MongoException, UnknownHostException{
return getMongo().getDatabaseNames();
}
/**
* 刪除數(shù)據(jù)庫
*/
public static void deleteDB(String DBName) throws MongoException, UnknownHostException{
getMongo().dropDatabase(DBName);
}