報錯信息:
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" }
經過查閱資料發現是使用了錯誤的授權賬號
MongoDB中每個數據庫之間是相互獨立的,都有獨立的權限,正確的做法是使用root賬號在【將要操作的數據庫】中創建一個【子賬號】,在用這個子賬號連接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"
}
]
}
最後在java代碼中的代入賬號、密碼等。