1、使用的是docker创建的mongodb

docker run --name mongodb0 -v /data/mongodb0:/data/db -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=root --privileged=true -e MONGO_INITDB_ROOT_PASSWORD=root -d mongo --auth

2、使用mongo-java-driver最新版驱动连接mongo库

<dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.11.0</version>
        </dependency>

3、因为设置了密码,通过直连会报错

new MongoClient("127.0.0.1");

报错信息如下 Authentication failed :

com.mongodb.MongoQueryException: Query failed with error code 13 and error message 'command find requires authentication' on server 127.0.0.1:27017
	at com.mongodb.operation.FindOperation$1.call(FindOperation.java:735)
	at com.mongodb.operation.FindOperation$1.call(FindOperation.java:725)
	at com.mongodb.operation.OperationHelper.withReadConnectionSource(OperationHelper.java:463)
	at com.mongodb.operation.FindOperation.execute(FindOperation.java:725)
	at com.mongodb.operation.FindOperation.execute(FindOperation.java:89)
	at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:189)
	at com.mongodb.client.internal.MongoIterableImpl.execute(MongoIterableImpl.java:143)
	at com.mongodb.client.internal.MongoIterableImpl.iterator(MongoIterableImpl.java:92)
	at com.xiangyanshan.MongoDemo.main(MongoDemo.java:55)

 

4、通过密码连接

之前创建的时候,创建的是root:root账号密码,所以

List<ServerAddress> adds = new ArrayList<>();
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
adds.add(serverAddress);

List<MongoCredential> credentials = new ArrayList<>();
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("root", "testdb", "root".toCharArray());
credentials.add(mongoCredential);

MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        //build.
        //通过连接认证获取MongoDB连接

MongoClientOptions options = MongoClientOptions.builder()
                //设置连接超时时间为10s
                .connectTimeout(1000*10)
                //设置最长等待时间为10s
                .maxWaitTime(1000*10)
                .build();

MongoClient client = new MongoClient(adds, credentials,options);

看起来没毛病,但是,报错,提示,认证失败

Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server 127.0.0.1:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}
	at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:175)
	at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:303)
	at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:259)
	at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
	at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
	at com.mongodb.internal.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:130)
	at com.mongodb.internal.connection.SaslAuthenticator.access$100(SaslAuthenticator.java:40)
	at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:54)
	... 21 more

5、新增新用户用于java连接

网上度娘了一圈,发现要创建新用户,于是,dos下连接到mongo库

mongo 127.0.0.1/admin -uroot -proot

一波命令操作猛于虎,一看结果气的抖

use admin

db.auth("root","root")

db.dbs 查看数据库
testdb

use testdb 使用数据库

db.createUser(
    {
            user:"java",
            pwd:"123456",
            roles:[{role:"dbOwner",db:"testdb"}]
    }
)

提示 Use of SCRAM-SHA-256 requires undigested passwords:

[thread1] Error: couldn't add user: Use of SCRAM-SHA-256 requires undigested passwords :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1267:15

继续度娘,发现需要修改mechanisms加密方式,增加 mechanisms : ["SCRAM-SHA-1"],执行成功

db.createUser(
    {
            user:"java",
            pwd:"123456",
            roles:[{role:"dbOwner",db:"testdb"}],
            mechanisms : ["SCRAM-SHA-1"]
    }
)

再修改用户名密码,连上

MongoCredential.createScramSha1Credential("java", "testdb", "123456".toCharArray());

总结:

这个连接从创建容器到java连接,尝试了很多次,作为一个程序员,一定要有耐心。慢慢研究下去终会成功。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐