简体   繁体   English

如何从MongoClient获取连接字符串中指定的Mongo数据库,Java

[英]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. 尽管我还没有尝试过。

  1. Use the getUsedDatabases method of MongoClient to get the database (ref: http://api.mongodb.com/java/2.10.1/com/mongodb/Mongo.html ) 使用MongoClient的getUsedDatabases方法获取数据库(参考: 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. 使用uri创建MongoClientURI的实例(参考: http ://api.mongodb.com/java/current/com/mongodb/MongoClientURI.html),然后在此对象上使用getDatabase()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有简单的方法从旧版 java MongoClient 中提取连接字符串 - Is there easy way to extract connection string from legacy java MongoClient 如何使用 MongoClient class 从 Mongo java 驱动程序调用 db.Collection.stats() - How to call db.Collection.stats() from Mongo java driver using MongoClient class 如何使用 Java mongoClient 将 InsertOneResult 转换为字符串 - How to convert InsertOneResult to string using Java mongoClient 如何从Java连接中获取查询字符串? - How to get query string from connection in Java? java如何从指定符号的字符串中获取列表? - java How to get the list from a string by the specified symbol? Java - 如何从 MongoDatabase 类获取 DB 对象,因为 MongoClient.getDB(dbName) 已弃用 - Java - How to get DB object from MongoDatabase class as MongoClient.getDB(dbName) is deprecated 如何从 FindIterable 中检索 Mongo 查询字符串(mongo java 驱动程序) - How to retrieve Mongo query string from FindIterable (mongo java driver) 如何从java.sql.Connection获取数据库URL? - How to get database url from java.sql.Connection? Java从服务器获取数据库连接 - Java get database connection from the server 如何从指定的字符串中提取值:java - How to extract value from a specified string : java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM