如何使用用户名和密码连接到Java中的MongoDB 3.2?
我在我的应用程序中使用 MongoDB
3.2。下面的代码演示了数据库初始化逻辑:
I'm using MongoDB
3.2 in my application. The code below demonstrates database initialization logic:
private void dbInit(String dbName) {
String mongoClientURI = "mongodb://" + DB_URL + ":" + DB_PORT;
MongoClientURI connectionString = new MongoClientURI(mongoClientURI);
// enable SSL connection
MongoClientOptions.builder().sslEnabled(true).build();
if (this.mongoClient == null) {
this.mongoClient = new MongoClient(connectionString);
}
// create database if doesn't exist
this.mongoClient.getDatabase(dbName);
}
此代码工作正常,现在我想将访问级别分离引入数据库。
This code works fine, now I want to introduce access level separation to database.
执行此操作的步骤:
-
定义用户:
Define users:
use myAppDB
db.createUser(
{
"user": "myAdmin",
"pwd": "123090d1487dd4ab7",
roles: [ "readWrite", "dbAdmin" ]
}
)
use myAppDB
db.createUser(
{
"user": "guest",
"pwd": "guest",
roles: [ "read" ]
}
)
重新创建 MongoDB
3.2验证模式下的服务:C:\Program Files \ MongoDB\Server\3.2\bin\mongod.exe--install - -dbpath = C:\data\db --logpath = C:\ data \log \log.txt --auth --service
。并运行它。
Re-create the MongoDB
3.2 service in authentification mode:
"C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe" --install --dbpath=C:\data\db --logpath=C:\data\log\log.txt --auth --service
. And run it.
将 mongoClientURI
连接字符串更改为
String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT;
其中 DB_SRV_USR
= myAdmin
和 DB_SRV_PWD
= 123090d1487dd4ab7
。
使用相同的凭据检查IDEA的 Mongo Explorer
中经过身份验证的连接,一切正常。
Check the authenticated connection in IDEA's Mongo Explorer
with the same credentials, everything is OK.
执行我的应用程序并获取异常验证失败
。
Execute my application and get exception Authentification failed
.
我的问题:
- 如何连接
MongoDB
3.2 in用户名和密码的Java?我看到了几个示例,但他们使用了弃用的方法。 - 我应该将我的用户添加到
myAppDB
或admin
表?在一些教程中,我看到用户是在admin
表中创建的,这是一个好主意还是值得在他们将要使用的数据库中创建用户?
- How to connect to
MongoDB
3.2 in Java with username and password? I saw a couple of examples but they are using deprecated methods. - Should I add my users to
myAppDB
or toadmin
table? In some tutorials I saw that users are created inadmin
table is it a good idea or it worth to create users only in a database they are going to work with?
as MarkusWMahlberg 正确注意到,有必要记下连接字符串中的数据库名称。
As MarkusWMahlberg correctly noted, it is necessary to note the database name in the connection string.
例如:
String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT + "/" + dbName;