Sunday, February 20, 2022

[SOLVED] Not able to connect mongodb by terminal using authentication data

Issue

Mongo version 5.0.2. Ubuntu 20.0

I have enabled security for MongoDB connection in my local host. I am trying to connect my localhost MongoDB using authentication details by below commands

mongo admin -u ADMIN_1234 -p "PASSWORD_1234" -host localhost:27017

mongo admin -u ADMIN_1234 -p "PASSWORD_1234" -host 127.0.0.1:27017

mongo admin -u ADMIN_1234 -p "PASSWORD_1234"

mongo admin -u ADMIN_1234 -p PASSWORD_1234 -host localhost:27017

mongo admin -u ADMIN_1234 -p PASSWORD_1234 -host 127.0.0.1:27017

mongo admin -u ADMIN_1234 -p PASSWORD_1234

but below error, I am getting for all the above commands. not able to connect to mongodb

connecting to: mongodb://localhost:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server localhost:27017, connection attempt failed: SocketException: Error connecting to localhost:27017 (127.0.0.1:27017) :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:372:17
@(connect):2:6
exception: connect failed
exiting with code 1

Solution

User either -u or --username. For host you have only long version, i.e. -h does not exist, it is used for "help". Use one of these ones (I prefer localhost rather than 127.0.0.1):

mongo -u ADMIN_1234 -p PASSWORD_1234 localhost:27017/admin
mongo -u ADMIN_1234 -p PASSWORD_1234 --authenticationDatabase admin localhost:27017
mongo -u ADMIN_1234 -p PASSWORD_1234 --host localhost --authenticationDatabase admin 
mongo -u ADMIN_1234 -p PASSWORD_1234 --host localhost --port 27017 --authenticationDatabase admin 

or use the connection string URI

mongo "mongodb://ADMIN_1234:PASSWORD_1234@localhost:27017/admin"


Answered By - Wernfried Domscheit
Answer Checked By - Mary Flores (WPSolving Volunteer)