MongoDB: Remote Connection – Command Line – Mongo Shell

From the following article you will find out how to connect to remote MongoDB server from the command line using mongo shell.

I will also show how to connect to remote MongoDB server with enabled auth.

First of you need to install mongo shell, ensure that MongoDB server allows remote access and if authentication is enabled, you need to know the credentials.

Cool Tip: To connect to a remote MongoDB server from the command line, it needs to install MongoDB command line client, known as mongo shell! Read More →

MongoDB: Remote Connection

Default Port: By default MongoDB is listening to port 27017.

Connect to remote MongoDB server:

$ mongo <HOST>
$ mongo <HOST>:<PORT>

Connect to remote MongoDB database:

$ mongo <HOST>:<PORT>/<DB>

You can also connect to remote MongoDB server with authentication by passing in user credentials on the command line.

Cool Tip: Enable authentication in MongoDB! Read More →

Connect to remote MongoDB server with authentication:

mongo -u <USER> -p <PASSWORD> <HOST>:<PORT> --authenticationDatabase <AUTH_DB>

Connect to remote MongoDB database with authentication:

mongo -u <USER> -p <PASSWORD> <HOST>:<PORT>/<DB> --authenticationDatabase <AUTH_DB>

When adding a user, you create the user in a specific database.

This database is the authentication database for the user.

A user can have privileges across different databases, this is why we specify the target database and the authentication database separately.

Authentication Database: If the option --authenticationDatabase it is not specified, mongo uses the database specified in the connection string.

Allow Remote Access

Out of the box, MongoDB has no authentication and is listening only on localhost on the default MongoDB port 27017:

If you won’t allow remote access to MongoDB, you may get this error:

Error: couldn’t connect to server $MongoDB:$Port, connection attempt failed:SocketException: Error connecting to $MongoDB:$Port :: caused by :: Connection refused … exception: connect failed

Cool Tip: To allow remote access to MongoDB – change bindIp! Read More →