我已经在连接字符串中指定了要连接的数据库,所以我希望不用硬编码就可以得到数据库实例。
但是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
最佳答案
随着modern API ,你可以使用:
String uri = "mongodb+srv://...";
String databaseName = new ConnectionString(uri).getDatabase();
Database database = mongoClient.getDatabase(databaseName);
关于java - 如何从 MongoClient, Java 获取连接字符串中指定的 Mongo 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48162917/