JaskeyLam
JaskeyLam

Reputation: 15785

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

Upvotes: 5

Views: 1437

Answers (2)

Ahmed Ashour
Ahmed Ashour

Reputation: 5559

With the modern API, you can use:

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

Upvotes: 3

Ankit Gupta
Ankit Gupta

Reputation: 325

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.

Upvotes: 0

Related Questions