当前位置:Gxlcms > 数据库问题 > 使用mongo-java-driver-3.0.2连接MongoDB数据库

使用mongo-java-driver-3.0.2连接MongoDB数据库

时间:2021-07-01 10:21:17 帮助过:13人阅读

utils; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientOptions.Builder; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; import com.mongodb.client.model.Filters; import com.mongodb.client.result.DeleteResult; /** * MongoDB工具类 Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够了<br> * 注意Mongo已经实现了连接池,并且是线程安全的。 <br> * 设计为单例模式, 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,<br> * Mongo有个内置的连接池(默认为10个) 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,<br> * DB和DBCollection是绝对线程安全的<br> * * @author gonglei 使用mongo-java-driver-3.0.2连接MongoDB数据库 * @date 2017-3-16 * @version 0.0.0 * @Copyright (c)2017-2018 */ public enum MongoDBUtil { /** * 定义一个枚举的元素,它代表此类的一个实例 */ instance; private MongoClient mongoClient; static { System.out.println("===============MongoDBUtil初始化========================"); /* CompositeConfiguration config = new CompositeConfiguration(); try { config.addConfiguration(new PropertiesConfiguration("mongodb.properties")); } catch (ConfigurationException e) { e.printStackTrace(); } */ // 从配置文件中获取属性值 String ip = utils.getWriteProperties.GetValueByKey("db.properties", "host"); int port = Integer.parseInt(utils.getWriteProperties.GetValueByKey("db.properties", "port")); // //默认写死 // String ip ="127.0.0.1"; // int port=27017; instance.mongoClient = new MongoClient(ip, port); // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members // List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018)); // instance.mongoClient = new MongoClient(listHost); // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码: // boolean auth = db.authenticate(myUserName, myPassword); Builder options = new MongoClientOptions.Builder(); // options.autoConnectRetry(true);// 自动重连true // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100 options.connectTimeout(15000);// 连接超时,推荐>3000毫秒 options.maxWaitTime(5000); // options.socketTimeout(0);// 套接字超时时间,0无限制 options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。 options.writeConcern(WriteConcern.SAFE);// options.build(); } // -----------------------------------共用方法--------------------------------------------------- /** * 获取DB实例 - 指定DB * * @param dbName * @return */ public MongoDatabase getDB(String dbName) { if (dbName != null && !"".equals(dbName)) { MongoDatabase database = mongoClient.getDatabase(dbName); return database; } return null; } /** * 获取collection对象 - 指定Collection * * @param collName * @return */ public MongoCollection<Document> getCollection(String dbName, String collName) { if (null == collName || "".equals(collName)) { return null; } if (null == dbName || "".equals(dbName)) { return null; } MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName); return collection; } /** * 查询DB下的所有表名 */ public List<String> getAllCollections(String dbName) { MongoIterable<String> colls = getDB(dbName).listCollectionNames(); List<String> _list = new ArrayList<String>(); for (String s : colls) { _list.add(s); } return _list; } /** * 获取所有数据库名称列表 * * @return */ public MongoIterable<String> getAllDBNames() { MongoIterable<String> s = mongoClient.listDatabaseNames(); return s; } /** * 删除一个数据库 */ public void dropDB(String dbName) { getDB(dbName).drop(); } /** * 查找对象 - 根据主键_id * * @param collection * @param id * @return */ public Document findById(MongoCollection<Document> coll, String id) { ObjectId _idobj = null; try { _idobj = new ObjectId(id); } catch (Exception e) { return null; } Document myDoc = coll.find(Filters.eq("_id", _idobj)).first(); return myDoc; } /** 统计数 */ public int getCount(MongoCollection<Document> coll) { int count = (int) coll.count(); return count; } /** 条件查询 */ public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) { return coll.find(filter).iterator(); } /** 分页查询 */ public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) { Bson orderBy = new BasicDBObject("_id", 1); return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator(); } /** * 通过ID删除 * * @param coll * @param id * @return */ public int deleteById(MongoCollection<Document> coll, String id) { int count = 0; ObjectId _id = null; try { _id = new ObjectId(id); } catch (Exception e) { return 0; } Bson filter = Filters.eq("_id", _id); DeleteResult deleteResult = coll.deleteOne(filter); count = (int) deleteResult.getDeletedCount(); return count; } /** * FIXME * * @param coll * @param id * @param newdoc * @return */ public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) { ObjectId _idobj = null; try { _idobj = new ObjectId(id); } catch (Exception e) { return null; } Bson filter = Filters.eq("_id", _idobj); // coll.replaceOne(filter, newdoc); // 完全替代 coll.updateOne(filter, new Document("$set", newdoc)); return newdoc; } public void dropCollection(String dbName, String collName) { getDB(dbName).getCollection(collName).drop(); } /** * 关闭Mongodb */ public void close() { if (mongoClient != null) { mongoClient.close(); mongoClient = null; } System.out.println("===============MongoDBUtil关闭连接========================"); }

  1. <span> /**
  2. * 测试插入数据库
  3. *
  4. * @param args
  5. */</span><br><span style="line-height: 1.5;"> public static void write(String HL7Msg)<br></span> {<br> String dbName = "testDBName";
  1. <em id="__mceDel"><em id="__mceDel"><em id="__mceDel"> String collName = "testcollName";</em></em></em>

       MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);

      //插入
       Document doc = new Document();
       doc.put("MsgID", "MSH-10");
       doc.put("HL7Body", HL7Msg );
       coll.insertOne(doc);
       }

  1. <span style="color: #008000;">/**</span><span style="color: #008000;">
  2. * 测试入口
  3. *
  4. * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> args
  5. </span><span style="color: #008000;">*/</span>
  6. <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> main(String[] args) {
  7. String dbName </span>= "testDBName"<span style="color: #000000;">;
  8. String collName </span>= "testcollName"<span style="color: #000000;">;
  9. MongoCollection</span><Document> coll =<span style="color: #000000;"> MongoDBUtil.instance.getCollection(dbName, collName);
  10. </span><span style="color: #008000;">//</span> <span style="color: #008000;">//</span><span style="color: #008000;">插入多条
  11. </span><span style="color: #008000;">//</span><span style="color: #008000;"> for (int i = 1; i <= 4; i++) {
  12. </span><span style="color: #008000;">//</span><span style="color: #008000;"> Document doc = new Document();
  13. </span><span style="color: #008000;">//</span><span style="color: #008000;"> doc.put("name", "yisheng");
  14. </span><span style="color: #008000;">//</span><span style="color: #008000;"> doc.put("school", "NEFU" + i);
  15. </span><span style="color: #008000;">//</span><span style="color: #008000;"> Document interests = new Document();
  16. </span><span style="color: #008000;">//</span><span style="color: #008000;"> interests.put("game", "game" + i);
  17. </span><span style="color: #008000;">//</span><span style="color: #008000;"> interests.put("ball", "ball" + i);
  18. </span><span style="color: #008000;">//</span><span style="color: #008000;"> doc.put("interests", interests);
  19. </span><span style="color: #008000;">//</span><span style="color: #008000;"> coll.insertOne(doc);
  20. </span><span style="color: #008000;">//</span><span style="color: #008000;"> }
  21. </span><span style="color: #008000;">//</span><span style="color: #008000;"> 根据ID查询</span>
  22. String id = "58caa7c21320c81bbcfc5593"<span style="color: #000000;">;
  23. Document doc </span>=<span style="color: #000000;"> MongoDBUtil.instance.findById(coll, id);
  24. System.out.println(doc);
  25. </span><span style="color: #008000;">//</span> <span style="color: #008000;">//</span><span style="color: #008000;">查询多个
  26. </span><span style="color: #008000;">//</span><span style="color: #008000;"> MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "yisheng")).iterator();
  27. </span><span style="color: #008000;">//</span><span style="color: #008000;"> while (cursor1.hasNext()) {
  28. </span><span style="color: #008000;">//</span><span style="color: #008000;"> org.bson.Document _doc = (Document) cursor1.next();
  29. </span><span style="color: #008000;">//</span><span style="color: #008000;"> System.out.println(_doc.toString());
  30. </span><span style="color: #008000;">//</span><span style="color: #008000;"> }
  31. </span><span style="color: #008000;">//</span><span style="color: #008000;"> cursor1.close();
  32. </span><span style="color: #008000;">//</span><span style="color: #008000;"> 查询多个
  33. </span><span style="color: #008000;">//</span><span style="color: #008000;"> MongoCursor<Person> cursor2 = coll.find(Person.class).iterator();
  34. </span><span style="color: #008000;">//</span> <span style="color: #008000;">//</span><span style="color: #008000;">删除数据库
  35. </span><span style="color: #008000;">//</span><span style="color: #008000;"> MongoDBUtil.instance.dropDB("testDBName");
  36. </span><span style="color: #008000;">//</span><span style="color: #008000;">删除表
  37. </span><span style="color: #008000;">//</span><span style="color: #008000;">MongoDBUtil2.instance.dropCollection(dbName, collName);
  38. </span><span style="color: #008000;">//</span> <span style="color: #008000;">//</span><span style="color: #008000;">修改数据
  39. </span><span style="color: #008000;">//</span><span style="color: #008000;"> String id = "58caa6041320c814f4520129";
  40. </span><span style="color: #008000;">//</span><span style="color: #008000;"> Document newdoc = new Document();
  41. </span><span style="color: #008000;">//</span><span style="color: #008000;"> newdoc.put("name", "龚lei");
  42. </span><span style="color: #008000;">//</span><span style="color: #008000;"> MongoDBUtil.instance.updateById(coll, id, newdoc);
  43. </span><span style="color: #008000;">//</span><span style="color: #008000;">统计表
  44. </span><span style="color: #008000;">//</span><span style="color: #008000;">System.out.println(MongoDBUtil.instance.getCount(coll));
  45. </span><span style="color: #008000;">//</span> <span style="color: #008000;">//</span><span style="color: #008000;">查询所有
  46. </span><span style="color: #008000;">//</span><span style="color: #008000;"> Bson filter = Filters.eq("count", 0);
  47. </span><span style="color: #008000;">//</span><span style="color: #008000;"> MongoDBUtil.instance.find(coll, filter);</span>
  48. <span style="color: #000000;">
  49. }
  50. }</span>

 

 

已测试。

 

使用mongo-java-driver-3.0.2连接MongoDB数据库

标签:指定   sem   private   key   central   版本   static   sheng   ntop   

人气教程排行