Why MongoDB doesn't allow to connect with the database specified?

All we need is an easy explanation of the problem, so here it is.

I installed MongoDB 4.4 on Ubuntu 20.04. Then, I created a user:

$ mongo
use admin
db.createUser({user:"admin",pwd:"foo",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})

Then, I configured security.authorization: enabled in /etc/mongod.conf and restarted it. Now I can connect like this:

$ mongo localhost:27017 -u admin -p foo

Works just fine. However, when I’m trying to connect and specify the database test to use, it fails with "Authentication failed":

$ mongo localhost:27017/test -u admin -p foo

What’s wrong?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

All authentication information is at admin -database.

When you use authentication and need to login to a different DB than the default, you need to tell mongo what is the authentication DB. This is done with parameter --authenticationDatabase admin.

So, in your case:

mongo localhost:27017/test -u admin -p foo --authenticationDatabase admin

Method 2

I solved this by running:

$ mongo
use test
db.createUser({user:"admin",pwd:"foo",roles:[{role:"dbOwner",db:"test"}]})

I still don’t understand the logic…

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply