详解MongoDB数据库基础操作及实例

  • A+
所属分类:MongoDB

详解数据库根基操作及实例

          废话不多说,直接上代码,注释写的比拟清晰,年夜家参考下,

 示例代码:

/** 
 * 插入一条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); 
} 

您可能感兴致的文章:

关于Mongodb 认证鉴权你必要知道的一些事linux体系下MongoDB单节点安装教程vue+socket.io+express+mongodb 实现简略单纯多房间在线群聊示例node.js操作MongoDB的实例详解windows7下使用MongoDB实现仓储设计java操作mongoDB查询的实例详解MongoDB若何查询耗时记载的办法详解MongoDB 3.4 安装以 Windows 服务方式运行的具体步调MongoDB TTL索引的实例详解

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: