'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. 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


Solution 1:[1]

I can think of two options. Although I haven't tried them.

  1. Use the getUsedDatabases method of MongoClient to get the database (ref: http://api.mongodb.com/java/2.10.1/com/mongodb/Mongo.html)
  2. 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.

Solution 2:[2]

With the modern API, you can use:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ankit Gupta
Solution 2