【问题标题】:How to get the Mongo database specified in connection string from MongoClient, Java如何从 MongoClient、Java 获取连接字符串中指定的 Mongo 数据库
【发布时间】:2018-01-09 07:05:21
【问题描述】:

我已经在连接字符串中指定了要连接的数据库,所以我希望我可以在没有硬编码的情况下获得数据库实例。

但是 mongoDbClient.getDatabase 方法需要数据库名称作为参数。有什么简单的方法吗?

   MongoClient mongoClient = new MongoClientURI(DispatcherConfigHolder.config.getMongoUrl());//I will put the uri in a config file so that I can change the db easily
   MongoDatabase db = ...//need a MongoDataBase here
   MongoCollection collection = db.getCollection("device");//so that I can access the collection from it

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    我可以想到两种选择。虽然我没试过。

    1. 使用MongoClient的getUsedDatabases方法获取数据库(参考:http://api.mongodb.com/java/2.10.1/com/mongodb/Mongo.html
    2. 使用 uri 创建一个 MongoClientURI 实例(参考:http://api.mongodb.com/java/current/com/mongodb/MongoClientURI.html),然后对该对象使用 getDatabase() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 2019-01-27
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多