[英]Java - How to get DB object from MongoDatabase class as MongoClient.getDB(dbName) is deprecated
Here is the old code:这是旧代码:
String uri = "mongodb://" + dbUser + ":" + dbPass + "@" + servers + "/"+dbName+ "?ssl=true&authSource=admin&connectTimeoutMS=6000&socketTimeoutMS=6000";
MongoClientURI uriObj = new MongoClientURI(uri);
MongoClient client = new MongoClient(uriObj);
DB db = client.getDB(dbName); ==> deprecated
Since MongoClient.getDB(dbName) is deprecated, here is the new code:由于 MongoClient.getDB(dbName) 已弃用,这里是新代码:
String uri = "mongodb://" + dbUser + ":" + dbPass + "@" + servers + "/"+dbName+ "?ssl=true&authSource=admin&connectTimeoutMS=6000&socketTimeoutMS=6000";
MongoClientURI uriObj = new MongoClientURI(uri);
MongoClient client = new MongoClient(uriObj);
MongoDatabase database = client.getDatabase(dbName); ==> How to get DB db?
How to get a DB object (as DB db in the old code) from the new code?如何从新代码中获取 DB 对象(如旧代码中的 DB db)?
Exactly your code DB db = mongoClient.getDB(dbName);
正是你的代码
DB db = mongoClient.getDB(dbName);
is for mongodb java drivers versions like 2.14.2
and 2.13.3
.适用于
2.14.2
和2.13.3
等 mongodb java 驱动程序版本。 Below is for newer, since 3.0.4
and 3.7.1
.下面是更新的,因为
3.0.4
和3.7.1
。
As mentioned in the documentation:如文档中所述:
Use MongoClients.create(), or MongoClient() for the legacy MongoClient API, to make a connection to a running MongoDB instance.
将 MongoClients.create() 或 MongoClient() 用于旧版 MongoClient API,以连接到正在运行的 MongoDB 实例。
up to version 3.7 (Legacy MongoClient API), you can use connection string and getDatabase() method to access a database like: 直到版本 3.7 (Legacy MongoClient API),您可以使用连接字符串和getDatabase()方法来访问数据库,例如:
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true"));
MongoDatabase database = mongoClient.getDatabase("db_name");
or by the same logic:或者按照同样的逻辑:
MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true");
MongoClient mongoClient = new MongoClient(uri);
MongoDatabase database = mongoClient.getDatabase("db_name");
New MongoClient API ( since 3.7 ) 新的 MongoClient API (自 3.7 起)
To make a connection to a running MongoDB instance and to access a database , you can use: 要连接到正在运行的 MongoDB 实例并访问数据库,您可以使用:
MongoClient mongoClient = MongoClients.create("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true");
MongoDatabase database = mongoClient.getDatabase("db_name");
Specify the name of the database to the getDatabase() method.
为 getDatabase() 方法指定数据库的名称。 If a database does not exist, MongoDB creates the database when you first store data for that database.
如果数据库不存在,MongoDB 会在您第一次为该数据库存储数据时创建该数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.