Error occurred when using java to connect mongodb: command failed with error 18 (authentication failed): “authentication failed.”

Error information:

Caused by: com.mongodb.MongoCommandException: Command failed with error 18: ‘Authentication failed.’ on server XXXXXXX:27017. The full response is { “ok” : 0.0, “errmsg” : “Authentication failed.”, “code” : 18, “codeName” : “AuthenticationFailed” }

After consulting the data, it is found that the wrong authorized account number has been used

Each database in mongodb is independent of each other and has independent permissions. The correct way is to use the root account to create a sub account in the database to be operated, and then use this sub account to connect Mongo

>use admin

switched to db admin

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

1

>show dbs

admin   0.000GB
config  0.000GB
good    0.000GB
local   0.000GB
test    0.000GB

>use good

switched to db good

> db.createUser({user:"daniel",pwd:"123456",roles:[{role:"dbOwner",db:"good"}]})
Successfully added user: {
        "user" : "daniel",
        "roles" : [
                {
                        "role" : "dbOwner",
                        "db" : "good"
                }
        ]
}

Finally, in the Java code into the account, password and so on.

Similar Posts: