详解MongoDB数据库基础操作及实例
详解数据库基础操作及实例
废话不多说,直接上代码,注释写的比较清楚,大家参考下,
示例代码:
/** *插入一条DB对象 */ publicstaticvoidaddDBObject(DBCollectioncollection,BasicDBObjectobject){ collection.insert(object); } /** *根据id查询DBObject */ publicstaticDBObjectgetDBObjectById(Stringvalue)throwsUnknownHostException,MongoException{ dbc=getDBCollection("company","users").find(newBasicDBObject("_id",newObjectId(value))); DBObjectob=null; inti=0; while(dbc.hasNext()){ ob=dbc.next(); i++; } if(i==1){ returnob; }else{ returnnull; } } /** *根据key和value值查询 */ publicstaticDBObjectgetDBObject(Stringkey,Stringvalue)throwsUnknownHostException,MongoException{ dbc=getDBCollection("company","users").find(newBasicDBObject(key,value)); DBObjectob=null; inti=0; while(dbc.hasNext()){ ob=dbc.next(); i++; } if(i==1){ returnob; }else{ returnnull; } } /** *根据数据库名获取(新增)下面所有聚集名(表名) */ publicstaticSetgetCollectionsNames(StringDBName)throwsMongoException,UnknownHostException{ returngetDB(DBName).getCollectionNames(); } /** *遍历聚集中的db对象集合(相当于关系数据库中的数据) */ publicstaticSet getDBObjects(DBCollectioncollection){ Set dbObjects=newHashSet (); DBCursorcursor=collection.find(); while(cursor.hasNext()){ DBObjectobject=cursor.next(); dbObjects.add(object); } returndbObjects; } /** *获取/新增聚集(相当于关系数据库表) */ publicstaticDBCollectiongetDBCollection(StringDBName,StringcollectionName)throwsUnknownHostException,MongoException{ returngetDB(DBName).getCollection(collectionName); } /** *获取/新增数据库 */ publicstaticDBgetDB(StringDBName)throwsUnknownHostException,MongoException{ returngetMongo().getDB(DBName); } /** *连接数据库 */ publicstaticMongogetMongo()throwsUnknownHostException,MongoException{ Mongomg=null; if(mg==null){ mg=newMongo(); } returnmg; } /** *关闭连接 */ publicstaticvoiddestory(Mongomg){ if(mg!=null){ mg.close(); mg=null; } System.gc(); } /** *获取数据库名 */ publicstaticList getDBNames()throwsMongoException,UnknownHostException{ returngetMongo().getDatabaseNames(); } /** *删除数据库 */ publicstaticvoiddeleteDB(StringDBName)throwsMongoException,UnknownHostException{ getMongo().dropDatabase(DBName); }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!