Introduction
Once you have a MongoDB server available, one of the first and most common actions you'll need to take is to connect to the actual database. This requires coordination to make sure that the database is configured in a way that allows your client to connect and authenticate.
This means that you'll need to understand how to connect to your MongoDB database by providing the server location, connection parameters, and the correct credentials. In this guide, we'll focus on how to connect to the database from the client side using the mongo
MongoDB shell client, designed mainly for interactive sessions with your databases.
In a companion guide, you can find out how to configure MongoDB's authentication settings to match your requirements. Consider reading both pieces for a complete picture of how authentication is implemented from the perspective of both parties.
If you're using MongoDB, checkout Prisma's MongoDB connector! You can use the Prisma Client to manage production MongoDB databases with confidence.
To get started working with MongoDB and Prisma, checkout our getting started from scratch guide or how to add to an existing project.
Basic information about the mongo
client
The mongo
client is a command line JavaScript client for connecting to, controlling, and interacting with MongoDB database servers. In many ways, it is the simplest way to connect to and start using your MongoDB database because it is included in the MongoDB installation and available on all popular platforms. The mongo
client is especially useful for performing initial configuration and for interactive sessions where you want to explore your data or iterate on queries based on preliminary results.
The way that you connect with the mongo
shell depends on the configuration of the MongoDB server and the options available for you to authenticate to an account. In the following sections, we'll go over some of the basic connection options. For clarity's sake, we'll differentiate between local and remote connections:
- local connection: a connection where the client and the MongoDB instance are located on the same server
- remote connection: where the client is connecting to a network-accessible MongoDB instance running on a different computer
Let's start with connecting to a database from the same computer.
Connecting to a local database with mongo
Without any arguments, the mongo
command attempts to connect to a local MongoDB instance.
To do this, it attempts to connect to port 27017 on the local loopback address: 127.0.0.1:27017
. This is one of the interfaces that MongoDB servers bind to in their default configuration (MongoDB may also be accessible through a local socket file).
You can connect to a local MongoDB server running with its default configuration by typing:
mongo
On a successful connection, you will likely see a fairly long set of messages followed by a MongoDB shell prompt:
MongoDB shell version v4.4.6connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodbImplicit session: session { "id" : UUID("9cf2d126-d25f-4ed8-b159-ef3bba4fcc53") }MongoDB server version: 4.4.6---The server generated these startup warnings when booting:2021-06-04T12:26:53.374+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem2021-06-04T12:26:54.562+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted------Enable MongoDB's free cloud-based monitoring service, which will then receive and displaymetrics about your deployment (disk utilization, CPU, operation statistics, etc).The monitoring data will be available on a MongoDB website with a unique URL accessible to youand anyone you share the URL with. MongoDB may use this information to make productimprovements and to suggest MongoDB products and deployment options to you.To enable free monitoring, run the following command: db.enableFreeMonitoring()To permanently disable this reminder, run the following command: db.disableFreeMonitoring()--->
The output shows logs generated by the mongo
command while establishing the connection, followed by some warnings generated by the MongoDB server on startup. Finally, there is a notice about a MongoDB monitoring service that you may choose to take advantage of or disable.
One of the warnings from the MongoDB server indicates that access control is not enabled currently. This is the reason we were able to connect without providing credentials or other authentication details.
If you are connecting to a local MongoDB server that has been configured with access control, you will need to provide additional information to connect. You will need to provide at least a username and password to connect using the associated --username
and --password
options:
mongo --username <mongo_username> --password
Placing the --password
option at the end and not providing the password inline indicates that you want MongoDB to prompt for a password instead. This is more secure than providing a password in the command itself as that may be visible or recoverable through shell history, process lists, and other mechanisms.
The MongoDB server will prompt you for the user's password before connecting to the database:
MongoDB shell version v.4.4.6Enter password:
Upon successfully authenticating, you should be connected to the database and able to continue your session as normal.
You can also provide this information by passing a connection string instead of using the --username
and --password
options:
mongo "mongodb://<mongo_username>:@127.0.0.1"
Since we've indicated that the user has a password with the <username>:
syntax, but haven't provided one, the mongo
shell will prompt for the password.
Alternatively, you can also authenticate after connecting with the normal mongo
command by using the db.auth
command.
First, connect to the MongoDB database without providing credentials:
mongo
You will be given a command prompt like usual, but if access control is enabled, you won't have permission perform many actions until you authenticate. For instance, the show dbs
command will likely be empty since you don't have access to query the available databases:
show dbs
To authenticate, first, select the database that your user is defined in. Most often, that will be the admin
database:
use admin
Afterwards, use db.auth()
to provide your username and request a password prompt:
db.auth({user: "<mongo_username>", passwordPrompt()})
You will be prompted for the user account's password as before:
Enter password:
If you are successful, the server will output 1
:
Enter password:1
You will now have the regular access of the user you authenticated as:
show dbs
admin 0.000GBconfig 0.000GBlocal 0.000GB
You can view the list authenticated users and roles associated with the current connection at any time by typing:
db.runCommand("connectionStatus")
{"authInfo" : {"authenticatedUsers" : [{"user" : "root","db" : "admin"}],"authenticatedUserRoles" : [{"role" : "userAdminAnyDatabase","db" : "admin"},{"role" : "readWriteAnyDatabase","db" : "admin"}]},"ok" : 1}
If you are looking to get started working with MongoDB and Prisma, checkout our getting started from scratch guide or how to add to an existing project.
Connecting to a remote database
If you want to connect to a remote MongoDB database, you'll have to provide some additional details when using the mongo
shell.
Specifically, you'll need to include the --host
option and potentially the --port
option as well if the MongoDB server is listening on a non-default port. In almost all cases, you'll also need to provide the --user
and --password
options to authenticate to the remote server too.
The basic structure of the command when connecting to a remote MongoDB database therefore looks something like this:
mongo --host <mongo_server_address> --port <mongo_server_port> --user <mongo_username> --password
As mentioned in the section on connecting to a local database, placing the --password
option at the end and not providing the password inline indicates that you want the mongo
shell to prompt for a password instead. This is more secure than providing a password in the command itself as that may be visible or recoverable through shell history, process lists, and other mechanisms.
The MongoDB server will prompt you for the user's password before connecting to the database:
MongoDB shell version v.4.4.6Enter password:
Upon successfully authenticating, you should be connected to the database and able to continue your session as normal.
You can also provide this information by passing a connection string instead of using the --host
, --port
, --username
and --password
options:
mongo "mongodb://<mongo_username>:@<mongo_server_address>:<mongo_server_port>"
Since we've indicated that the user has a password with the <username>:
syntax, but haven't provided one, the mongo
shell will prompt for the password.
Adjusting a MongoDB server's authentication configuration
If you want to modify the rules that dictate how users can authenticate to your MongoDB instances, you can do so by modifying your server's configuration. You can find out how to modify MongoDB's authentication configuration in this article.
Conclusion
In this guide, we covered MongoDB authentication from the client side. We demonstrated how to use the mongo
shell to connect to both local and remote database instances using a variety of methods.
Knowing how to connect to various MongoDB instances is vital as you start to work the database system. You may run a local MongoDB instance for development that doesn't need any special authentication, but your databases in staging and production will almost certainly require authentication. Being able to authenticate in either case will allow you to work well in different environments.
If you're using MongoDB, checkout Prisma's MongoDB connector! You can use the Prisma Client to manage production MongoDB databases with confidence.
To get started working with MongoDB and Prisma, checkout our getting started from scratch guide or how to add to an existing project.
FAQ
Whether connecting to MongoDB locally or remotely, a connection failure will result in an error message from MongoDB. The most common sources of a connection error are an incorrect username or password, attempting to connect with a non-whitelisted IP address, or potentially too many connections to the database.
You can read more about connecting to MongoDB database to ensure you have all of the necessary pieces.
To connect to a remote MongoDB database, you have to include additional details when using the mongo
shell like --host
and potentially --port
.
The basic structure of the command will look something like:
mongo --host <mongo_server_address> --port <mongo_server_port> --user <mongo_username> --password
Your MongoDB database also will need to be configured to accept remote connections either in the configuration file or the Atlas IP whitelist.
Assuming the admin user has already been created using these steps, you can use something similar to the following syntax:
use admindb.auth('admin','password');
The mongo
client is a command line JavaScript client for connecting to, controlling, and interacting with MongoDB database servers.
The way you connect and use the mongo
shell will depend on your configuration, but you can generally begin by using the command line by typing mongo
into the shell.
MongoDB also has the --help
add-on from the command line if needed.
Yes, you can connect to MongoDB with Java. The first step in the procedure will require installing the Java driver.