Title: How to get the Mongo database specified in connection string from MongoClient, Java
Tags: java;mongodb
Question: 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. 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(&quot;device&quot;);//so that I can access the collection from it

Here is the accepted answer: I can think of two options. Although I haven't tried them.
Use the getUsedDatabases method of MongoClient to get the database (ref: http://api.mongodb.com/java/2.10.1/com/mongodb/Mongo.html)
Create an instance of MongoClientURI (ref: http://api.mongodb.com/java/current/com/mongodb/MongoClientURI.html) using the uri and then use the method getDatabase() on this object.

Here is another answer: With the modern API, you can use:
String uri = &quot;mongodb+srv://...&quot;;
String databaseName = new ConnectionString(uri).getDatabase();
Database database = mongoClient.getDatabase(databaseName);

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:01/09/18', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<java><mongodb>', 'Title': 'How to get the Mongo database specified in connection string from MongoClient, Java', 'ViewCount': 361, 'id': 48162917, 'user_AboutMe': '<p>blog: <a href="https://jaskey.github.io" rel="nofollow noreferrer">jaskey.github.io</a></p>\n', 'user_AccountId': 2386817.0, 'user_DisplayName': 'JaskeyLam', 'user_Reputation': 14663.0, 'user_Views': 1012.0, 'user_id': 2087628.0}}