[英]How to get the Mongo database specified in connection string from MongoClient, Java
I have already specified the database to connect in the connection string, so I hope I can get the database instance without hard coded.我已经在连接字符串中指定了要连接的数据库,所以我希望我不需要硬编码就可以得到数据库实例。
But the method mongoDbClient.getDatabase needs the database name as the parameter.但是方法 mongoDbClient.getDatabase 需要数据库名称作为参数。 Is there any easy way to do that?有没有简单的方法可以做到这一点?
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
With the modern API , you can use:使用现代 API ,您可以使用:
String uri = "mongodb+srv://...";
String databaseName = new ConnectionString(uri).getDatabase();
Database database = mongoClient.getDatabase(databaseName);
I can think of two options. 我可以想到两个选择。 Although I haven't tried them. 尽管我还没有尝试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.