mongodb objetcid_JAVA 操作MongoDB

1 packagecom.wd.util;2

3 importjava.util.ArrayList;4 importjava.util.Arrays;5 importjava.util.List;6 importorg.bson.Document;7 importorg.bson.conversions.Bson;8 importorg.bson.types.ObjectId;9

10 importcom.mongodb.BasicDBObject;11 importcom.mongodb.DB;12 importcom.mongodb.DBCollection;13 importcom.mongodb.DBCursor;14 importcom.mongodb.MongoClient;15 importcom.mongodb.MongoClientOptions;16 importcom.mongodb.MongoClientOptions.Builder;17 importcom.mongodb.WriteConcern;18 importcom.mongodb.client.AggregateIterable;19 importcom.mongodb.client.FindIterable;20 importcom.mongodb.client.ListIndexesIterable;21 importcom.mongodb.client.MongoCollection;22 importcom.mongodb.client.MongoCursor;23 importcom.mongodb.client.MongoDatabase;24 importcom.mongodb.client.MongoIterable;25 importcom.mongodb.client.model.Filters;26 import static com.mongodb.client.model.Filters.*;27 import static com.mongodb.client.model.Projections.*;28 import static com.mongodb.client.model.Sorts.*;29 import static com.mongodb.client.model.Accumulators.*;30 import static com.mongodb.client.model.Aggregates.*;31 importcom.mongodb.client.model.IndexOptions;32 importcom.mongodb.client.model.Projections;33 importcom.mongodb.client.model.UpdateOptions;34 import com.mongodb.client.model.Updates.*;35 importcom.mongodb.client.result.DeleteResult;36 importcom.wd.backend.model.AffiliationJG;37 importcom.wd.backend.model.AffiliationList;38

39 importnet.sf.json.JSONArray;40 importnet.sf.json.JSONObject;41 importnet.sf.json.JsonConfig;42

43

44 public enumMongoUtil {45 /**

46 * 定义一个枚举的元素,它代表此类的一个实例47 */

48 instance;49

50 private staticMongoClient mongoClient;51

52 static{53 System.out.println("===============MongoDBUtil初始化========================");54 String ip = "192.168.1.75";55 int port =27017;56 instance.mongoClient = newMongoClient(ip, port);57 //大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:58 //boolean auth = db.authenticate(myUserName, myPassword);

59 Builder options = newMongoClientOptions.Builder();60 options.cursorFinalizerEnabled(true);61 //options.autoConnectRetry(true);//自动重连true62 //options.maxAutoConnectRetryTime(10);//the maximum auto connect retry time

63 options.connectionsPerHost(300);//连接池设置为300个连接,默认为100

64 options.connectTimeout(30000);//连接超时,推荐>3000毫秒

65 options.maxWaitTime(5000); //66 options.socketTimeout(0);//套接字超时时间,0无限制

67 options.threadsAllowedToBlockForConnectionMultiplier(5000);//线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。

68 options.writeConcern(WriteConcern.SAFE);//69 options.build();70 }71

72 //------------------------------------共用方法---------------------------------------------------

73 /**

74 * 获取DB实例 - 指定DB75 *76 *@paramdbName77 *@return

78 */

79 publicMongoDatabase getDB(String dbName) {80 if (dbName != null && !"".equals(dbName)) {81 MongoDatabase database =mongoClient.getDatabase(dbName);82 returndatabase;83 }84 return null;85 }86

87 /**

88 * 获取collection对象 - 指定Collection89 *90 *@paramcollName91 *@return

92 */

93 public MongoCollectiongetCollection(String dbName, String collName) {94 if (null == collName || "".equals(collName)) {95 return null;96 }97 if (null == dbName || "".equals(dbName)) {98 return null;99 }100 MongoCollection collection =mongoClient.getDatabase(dbName).getCollection(collName);101 returncollection;102 }103

104 /**

105 * 查询DB下的所有表名106 */

107 public ListgetAllCollections(String dbName) {108 MongoIterable colls =getDB(dbName).listCollectionNames();109 List _list = new ArrayList();110 for(String s : colls) {111 _list.add(s);112 }113 return_list;114 }115

116 /**

117 * 获取所有数据库名称列表118 *119 *@return

120 */

121 public MongoIterablegetAllDBNames() {122 MongoIterable s =mongoClient.listDatabaseNames();123 returns;124 }125

126 /**

127 * 删除一个数据库128 */

129 public voiddropDB(String dbName) {130 getDB(dbName).drop();131 }132

133 /**

134 * 查找对象 - 根据主键_id135 *136 *@paramcollection137 *@paramid138 *@return

139 */

140 public Document findById(MongoCollectioncoll, String id) {141 ObjectId _idobj = null;142 try{143 _idobj = newObjectId(id);144 } catch(Exception e) {145 return null;146 }147 Document myDoc = coll.find(Filters.eq("_id", _idobj)).first();148 returnmyDoc;149 }150

151 /**统计数*/

152 public int getCount(MongoCollectioncoll) {153 int count = (int) coll.count();154 returncount;155 }156

157 /**条件查询*/

158 public MongoCursor find(MongoCollectioncoll, Bson filter) {159 returncoll.find(filter).iterator();160 }161

162 /**分页查询*/

163 public MongoCursor findByPage(MongoCollection coll, Bson filter, int pageNo, intpageSize) {164 Bson orderBy = new BasicDBObject("_id", 1);165 return coll.find(filter).sort(orderBy).skip((pageNo - 1) *pageSize).limit(pageSize).iterator();166 }167

168

169 /**

170 * 通过ID删除171 *172 *@paramcoll173 *@paramid174 *@return

175 */

176 public int deleteById(MongoCollectioncoll, String id) {177 int count = 0;178 ObjectId _id = null;179 try{180 _id = newObjectId(id);181 } catch(Exception e) {182 return 0;183 }184 Bson filter = Filters.eq("_id", _id);185 DeleteResult deleteResult =coll.deleteOne(filter);186 count = (int) deleteResult.getDeletedCount();187 returncount;188 }189

190 /**

191 * FIXME192 *193 *@paramcoll194 *@paramid195 *@paramnewdoc196 *@return

197 */

198 public Document updateById(MongoCollectioncoll, String id, Document newdoc) {199 ObjectId _idobj = null;200 try{201 _idobj = newObjectId(id);202 } catch(Exception e) {203 return null;204 }205 Bson filter = Filters.eq("_id", _idobj);206 //coll.replaceOne(filter, newdoc);//完全替代

207 coll.updateOne(filter, new Document("$set", newdoc));208 returnnewdoc;209 }210

211 public voiddropCollection(String dbName, String collName) {212 getDB(dbName).getCollection(collName).drop();213 }214

215 /**

216 * 关闭Mongodb217 */

218 public voidclose() {219 if (mongoClient != null) {220 mongoClient.close();221 mongoClient = null;222 }223 }224

225 /**

226 * 测试入口227 *228 *@paramargs229 *@throwsCloneNotSupportedException230 */

231 public static voidmain(String[] args) {232

233 String dbName = "test";234 String collName = "wd_paper_scie";235 MongoCollection coll =MongoUtil.instance.getCollection(dbName, collName);236 //coll.createIndex(new Document("validata",1));//创建索引237 //coll.createIndex(new Document("id",1));238 //coll.createIndex(new Document("ut_wos",1),new IndexOptions().unique(true));//创建唯一索引239 //coll.dropIndexes();//删除索引240 //coll.dropIndex("validata_1");//根据索引名删除某个索引

241 ListIndexesIterable list = coll.listIndexes();//查询所有索引

242 for(Document document : list) {243 System.out.println(document.toJson());244 }245 coll.find(Filters.and(Filters.eq("x", 1), Filters.lt("y", 3)));246 coll.find(and(eq("x", 1), lt("y", 3)));247 coll.find().sort(ascending("title"));248 coll.find().sort(new Document("id",1));249 coll.find(new Document("$or", Arrays.asList(new Document("owner", "tom"), new Document("words", new Document("$gt", 350)))));250 coll.find().projection(fields(include("title", "owner"), excludeId()));251 //coll.updateMany(Filters.eq("validata", 1), Updates.set("validata", 0));252 //coll.updateMany(Filters.eq("validata", 1), new Document("$unset", new Document("jigou", "")));//删除某个字段253 //coll.updateMany(Filters.eq("validata", 1), new Document("$rename", new Document("affiliation", "affiliation_full")));//修改某个字段名254 //coll.updateMany(Filters.eq("validata", 1), new Document("$rename", new Document("affiliationMeta", "affiliation")));255 //coll.updateMany(Filters.eq("validata", 1), new Document("$set", new Document("validata", 0)));//修改字段值256 //MongoCursor cursor1 =coll.find(Filters.eq("ut_wos", "WOS:000382970200003")).iterator();257 //while(cursor1.hasNext()){258 //Document sd=cursor1.next();259 //System.out.println(sd.toJson());260 //coll.insertOne(sd);261 //}262

263 //MongoCursor cursor1 =coll.find(Filters.elemMatch("affInfo", Filters.eq("firstorg", 1))).iterator();264 //while(cursor1.hasNext()){265 //Document sd=cursor1.next();266 //System.out.println(sd.toJson());267 //}268 //查询只返回指定字段269 //MongoCursor doc= coll.find().projection(Projections.fields(Projections.include("ut_wos","affiliation"),Projections.excludeId())).iterator();270 //"ut_wos" : "WOS:000382970200003"271 //coll.updateMany(Filters.eq("validata", 1), new Document("$set", new Document("validata", 0)));272 //coll.updateMany(Filters.eq("validata", 0), new Document("$rename", new Document("sid", "ssid")), new UpdateOptions().upsert(false));273 //coll.updateOne(Filters.eq("ut_wos", "WOS:000382970200003"), new Document("$set", new Document("validata", 0)));274 //long isd=coll.count(Filters.elemMatch("affInfo", Filters.elemMatch("affiliationJGList", Filters.eq("sid", 0))));275 //System.out.println(isd);276 //MongoCursor doc= coll.find(Filters.elemMatch("affInfo", Filters.elemMatch("affiliationJGList", Filters.ne("sid", 0)))).projection(Projections.fields(Projections.elemMatch("affInfo"),Projections.excludeId())).iterator();277 //MongoCursor doc= coll.find().projection(Projections.include("affInfo","ssid")).iterator();278 //while(doc.hasNext()){279 //Document sd=doc.next();280 //System.out.println(sd.toJson());281 //

282 //}

283 MongoUtil.instance.close();284 //插入多条285 //for (int i = 1; i <= 4; i++) {286 //Document doc = new Document();287 //doc.put("name", "zhoulf");288 //doc.put("school", "NEFU" + i);289 //Document interests = new Document();290 //interests.put("game", "game" + i);291 //interests.put("ball", "ball" + i);292 //doc.put("interests", interests);293 //coll.insertOne(doc);294 //}295 //

296 /*MongoCursor sd =coll.find().iterator();297 while(sd.hasNext()){298 Document doc = sd.next();299 String id = doc.get("_id").toString();300 List list = new ArrayList();301 AffiliationJG jg = new AffiliationJG();302 jg.setAddress("123");303 jg.setCid(2);304 jg.setCname("eeee");305 jg.setSid(3);306 jg.setSname("rrrr");307 AffiliationJG jg2 = new AffiliationJG();308 jg2.setAddress("3242");309 jg2.setCid(2);310 jg2.setCname("ers");311 jg2.setSid(3);312 jg2.setSname("rasdr");313 list.add(jg);314 list.add(jg2);315 AffiliationList af = new AffiliationList();316 af.setAffiliationAuthos("33333");317 af.setAffiliationinfo("asdsa");318 af.setAffiliationJGList(list);319 JSONObject json = JSONObject.fromObject(af);320 doc.put("affInfo", json);321 MongoDBUtil.instance.updateById(coll, id, doc);322 }*/

323

324 //Bson bs = Filters.eq("name", "zhoulf");325 //coll.find(bs).iterator();326 // //根据ID查询327 //String id = "556925f34711371df0ddfd4b";328 //Document doc = MongoDBUtil2.instance.findById(coll, id);329 //System.out.println(doc);330

331 //查询多个332 //MongoCursor cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();333 //while (cursor1.hasNext()) {334 //org.bson.Document _doc = (Document) cursor1.next();335 //System.out.println(_doc.toString());336 //}337 //cursor1.close();338

339 //查询多个340 //MongoCursor cursor2 = coll.find(WdPaper.class).iterator();341 //while(cursor2.hasNext()){342 //WdPaper doc = cursor2.next();343 //System.out.println(doc.getUt_wos());344 //}345 //删除数据库346 //MongoDBUtil2.instance.dropDB("testdb");347

348 //删除表349 //MongoDBUtil2.instance.dropCollection(dbName, collName);350

351 //修改数据352 //String id = "556949504711371c60601b5a";353 //Document newdoc = new Document();354 //newdoc.put("name", "时候");355 //MongoDBUtil.instance.updateById(coll, id, newdoc);356

357 //统计表358 //System.out.println(MongoDBUtil.instance.getCount(coll));359

360 //查询所有361 //Bson filter = Filters.eq("count", 0);362 //MongoDBUtil.instance.find(coll, filter);

363

364 }365

366 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值