Connecting to a database in a cluster MongoDB

You can connect to Managed Service for MongoDB cluster hosts:

  • Over the internet, if you configured public access for the appropriate host. You can only connect to these hosts over an SSL connection.
  • From Yandex.Cloud virtual machines located in the same virtual network. If the host isn't publicly available, you don't need to use an SSL connection to connect to such VMs.

To connect to Managed Service for MongoDB cluster hosts, specify port 27018.

Note

If public access is only configured for certain hosts in your cluster, automatic primary replica change may make the primary replica unavailable over the internet.

Configuring an SSL certificate

MongoDBhosts with public access only support connections with an SSL certificate. You can prepare a certificate as follows:

$ mkdir ~/.mongodb
$ wget "https://storage.yandexcloud.net/cloud-certs/CA.pem" -O ~/.mongodb/CA.pem
$ chmod 0600 ~/.mongodb/CA.pem

Connection string

You can connect to the database using the command mongo by listing all the cluster hosts in the host parameter value.

To view an example of the command with the host FQDN filled in, open the cluster page in the management console and click Connect.

For hosts with public access, you can only connect over the internet with an SSL certificate.

$ mongo --norc \
        --tls \
        --tlsCAFile ~/.mongodb/CA.pem \
        --host 'rs01/<host 1 FQDN>:27018,<host 2 FQDN>:27018,<host N FQDN>:27018' \
        -u <user name> \
        -p <user password> \
        <DB name>

For hosts with public access, you can only connect over the internet with an SSL certificate.

$ mongo --norc \
        --ssl \
        --sslCAFile ~/.mongodb/CA.pem \
        --host 'rs01/<host 1 FQDN>:27018,<host 2 FQDN>:27018,<host N FQDN>:27018' \
        -u <user name> \
        -p <user password> \
        <DB name>

If you don't need to encrypt traffic within the virtual network when connecting to the database, you can connect from a Yandex.Cloud VM without SSL. Pass the sslmode parameter with the disable value:

$ mongo --norc \
        --host 'rs01/<host 1 FQDN>:27018,<host 2 FQDN>:27018,<host N FQDN>:27018' \
        -u <user name> \
        -p <user password> \
        <DB name>

Write requests will be automatically routed to the primary cluster replica.