繁体   English   中英

如何从MongoClient获取连接字符串中指定的Mongo数据库,Java

[英]How to get the Mongo database specified in connection string from MongoClient, Java

我已经在连接字符串中指定了要连接的数据库,所以我希望我不需要硬编码就可以得到数据库实例。

但是方法 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

使用现代 API ,您可以使用:

String uri = "mongodb+srv://...";
String databaseName = new ConnectionString(uri).getDatabase();
Database database = mongoClient.getDatabase(databaseName);

我可以想到两个选择。 尽管我还没有尝试过。

  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()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM