Connecting to a non-sharded MongoDB cluster
Connecting from graphical IDEs
Connections were tested in the following environment:
- MacOS Big Sur 11.3.
- JetBrains DataGrip:
2021.1
. - DBeaver Enterprise:
21.0
.
You can only use graphical IDEs to connect to public cluster hosts using SSL certificates.
To avoid connection errors, save the certificate
- Create a data source:
- Select File → New → Data Source → MongoDB.
- On the General tab:
-
Specify the connection parameters:
-
User, Password: DB user's name and password.
-
URL: Connection string:
mongodb://<FQDN_of_MongoDB_host_1>:27018,..,<FQDN_of_MongoDB_host_N>:27018/<DB_name>
To learn how to get a host FQDN, see this guide.
-
-
Click Download to download the connection driver.
-
- On the SSH/SSL tab:
- Enable the Use SSL setting.
- In the CA file field, specify the path to the file with an SSL certificate for the connection.
- Click Test Connection to test the connection. If the connection is successful, you will see the connection status and information about the DBMS and driver.
- Click OK to save the data source.
Connections to MongoDB clusters are only available in commercial versions of DBeaver
To connect to a cluster:
- Create a new DB connection:
- In the Database menu, select New connection.
- Select MongoDB from the DB list.
- Click Next.
- Specify the connection parameters on the Main tab:
-
Under Address, change the Type value to
URL
and specify the connection string:mongodb://<FQDN_of_MongoDB_host_1>:27018,..,<FQDN_of_MongoDB_host_N>:27018/<DB_name>
To learn how to get a host FQDN, see this guide.
-
In the Device list, select
SCRAM-SHA-256
(type of password encryption when connecting to the DB). -
Under Authentication, specify the DB username and password.
-
- On the SSL tab:
- Enable Use SSL.
- In the Root certificate field, specify the path to the saved SSL certificate file.
- Under Settings, select Skip hostname validation.
- Click Test connection ... to test the connection. If the connection is successful, you will see the connection status and information about the DBMS and driver.
- Click Ready to save the database connection settings.
Before you connect from a Docker container
To connect to a Managed Service for MongoDB cluster from a Docker container using SSL, add the following lines to the Dockerfile:
RUN apt-get update && \
apt-get install wget --yes && \
mkdir --parents ~/.mongodb && \
wget "https://storage.yandexcloud.net/cloud-certs/CA.pem" \
--output-document ~/.mongodb/root.crt && \
chmod 0644 ~/.mongodb/root.crt
To connect without SSL, no additional Dockerfile settings are required.
After running the Docker container, switch to it and installmongosh
utility. You will need it to connect to the cluster.
Sample connection strings
The Linux examples were tested in the following environment:
- Yandex Cloud virtual machine running Ubuntu 20.04 LTS.
- Bash:
5.0.16
. - Python:
3.8.2
; pip3:20.0.2
. - PHP:
7.4.3
. - OpenJDK:
11.0.8
; Maven:3.6.3
. - Node.JS:
10.19.0
, npm:6.14.4
. - Go:
1.13.8
. - Ruby:
2.7.0p0
. - unixODBC:
2.3.6
.
The Windows examples were tested in the following environment:
- A local machine with Windows 10 Pro build
19042.1052
. - PowerShell:
5.1.19041
. - cURL:
7.55.1 WinSSL
.
To view an example of the command with the host FQDN filled in, open the cluster page in the management console
The examples below assume that the root.crt
SSL certificate is located in the directory:
/home/<home_directory>/.mongodb/
for Ubuntu.$HOME\.mongodb
for Windows.
If the connection to the cluster and the test query are successful, the following data is output:
- For PHP examples, the
ping
command result. - For other examples, the name of the database the connection was established to.
Bash
Before connecting, install the MongoDB Shell utility
mongosh --norc \
--tls \
--tlsCAFile /home/<home_directory>/.mongodb/root.crt \
--host '<FQDN_of_MongoDB_host_1>:27018,...,<FQDN_of_MongoDB_host_N>:27018' \
--username <DB_username> \
--password <DB_user_password> \
<DB_name>
mongosh --norc \
--ssl \
--sslCAFile /home/<home_directory>/.mongodb/root.crt \
--host '<FQDN_of_MongoDB_host_1>:27018,...,<FQDN_of_MongoDB_host_N>:27018' \
--username <DB_username> \
--password <DB_user_password> \
<DB_name>
mongosh --norc \
--host '<FQDN_of_MongoDB_host_1>:27018,...,<FQDN_of_MongoDB_host_N>:27018' \
--username <DB_username> \
--password <DB_user_password> \
<DB_name>
To learn how to get a host FQDN, see this guide.
After connecting, run the db
command.
Go
Before connecting, install the dependencies:
sudo apt update && sudo apt install --yes golang git && \
go get go.mongodb.org/mongo-driver/mongo
connect.go
package main
import (
"fmt"
"strings"
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
const DB_RS = "<replica_set_name>"
const DB_NAME = "<DB_name>"
DB_HOSTS := []string {"<FQDN_of_MongoDB_host_1>:27018",
...,
"<FQDN_of_MongoDB_host_N>:27018"}
const DB_USER = "<DB_username>"
const DB_PASS = "<DB_user_password>"
const CACERT = "/home/<home directory>/.mongodb/root.crt"
url := fmt.Sprintf("mongodb://%s:%s@%s/%s?replicaSet=%s&tls=true&tlsCaFile=%s",
DB_USER,
DB_PASS,
strings.Join(DB_HOSTS, ","),
DB_NAME,
DB_RS,
CACERT)
conn, err := mongo.Connect(context.Background(), options.Client().ApplyURI(url))
if err != nil {
panic(err)
}
defer conn.Disconnect(context.Background())
fmt.Println(conn.Database(DB_NAME).Name())
}
connect.go
package main
import (
"fmt"
"strings"
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
const DB_RS = "<replica_set_name>"
const DB_NAME = "<DB_name>"
DB_HOSTS := []string {"<FQDN_of_MongoDB_host_1>:27018",
...,
"<FQDN_of_MongoDB_host_N>:27018"}
const DB_USER = "<DB_username>"
const DB_PASS = "<DB_user_password>"
url := fmt.Sprintf("mongodb://%s:%s@%s/%s?replicaSet=%s&tls=false",
DB_USER,
DB_PASS,
strings.Join(DB_HOSTS, ","),
DB_NAME,
DB_RS)
conn, err := mongo.Connect(context.Background(), options.Client().ApplyURI(url))
if err != nil {
panic(err)
}
defer conn.Disconnect(context.Background())
fmt.Println(conn.Database(DB_NAME).Name())
}
To learn how to get a host FQDN, see this guide.
Connecting:
go run connect.go
Java
Before connecting:
-
Install the dependencies:
sudo apt update && sudo apt install --yes default-jdk maven
-
Add the SSL certificate to the Java trusted certificate store (Java Key Store) so that the MongoDB driver can use this certificate for secure connections to the cluster hosts. Make sure to set the password for additional storage security using the
-storepass
parameter:cd ~/.mongodb && \ sudo keytool -importcert \ -alias YandexCA -file root.crt \ -keystore ssl -storepass <password> \ --noprompt
Where
storepass
is the certificate store password, at least 6 characters long. -
Create a folder for the Maven project:
cd ~/ && \ mkdir --parents project/src/java/com/example && \ cd ~/project
-
Create a configuration file for Maven:
pom.xml<?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>app</artifactId> <packaging>jar</packaging> <version>0.1.0</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.30</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}-${project.version}</finalName> <sourceDirectory>src</sourceDirectory> <resources> <resource> <directory>src</directory> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <goals> <goal>attached</goal> </goals> <phase>package</phase> <configuration> <descriptorRefs> <descriptorRef> jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>com.example.App</mainClass> </manifest> </archive> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.0</version> <configuration> <archive> <manifest> <mainClass>com.example.App</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> </project>
Up-to-date versions of dependencies for Maven:
src/java/com/example/App.java
package com.example;
import java.util.*;
import com.mongodb.*;
import com.mongodb.client.*;
public class App {
public static void main(String[] args) {
System.setProperty("javax.net.ssl.trustStore", "/home/<home_directory>/.mongodb/YATrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "<certificate_store_password>");
final Integer DB_PORT = 27018;
List DB_HOSTS = new ArrayList<ServerAddress>();
DB_HOSTS.add(new ServerAddress("<FQDN_of_MongoDB_host_1>", DB_PORT));
...,
DB_HOSTS.add(new ServerAddress("<FQDN_of_MongoDB_host_N>", DB_PORT));
final String DB_NAME = "<DB_name>";
final String DB_USER = "<DB_username>";
final String DB_PASS = "<DB_user_password>";
MongoClient conn = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder -> builder.hosts(DB_HOSTS))
.applyToSslSettings(builder -> builder.enabled(true))
.credential(MongoCredential.createCredential(DB_USER, DB_NAME, DB_PASS.toCharArray()))
.build());
System.out.println(conn.getDatabase(DB_NAME).getName());
conn.close();
}
}
src/java/com/example/App.java
package com.example;
import java.util.*;
import com.mongodb.*;
import com.mongodb.client.*;
public class App {
public static void main(String[] args) {
final Integer DB_PORT = 27018;
List DB_HOSTS = new ArrayList<ServerAddress>();
DB_HOSTS.add(new ServerAddress("<FQDN_of_MongoDB_host_1>", DB_PORT));
...,
DB_HOSTS.add(new ServerAddress("<FQDN_of_MongoDB_host_N>", DB_PORT));
final String DB_NAME = "<DB_name>";
final String DB_USER = "<DB_username>";
final String DB_PASS = "<DB_user_password>";
MongoClient conn = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder -> builder.hosts(DB_HOSTS))
.credential(MongoCredential.createCredential(DB_USER, DB_NAME, DB_PASS.toCharArray()))
.build());
System.out.println(conn.getDatabase(DB_NAME).getName());
conn.close();
}
}
To learn how to get a host FQDN, see this guide.
Connecting:
mvn clean package && \
java -jar target/app-0.1.0-jar-with-dependencies.jar
Node.js
Before connecting, install the dependencies:
sudo apt update && sudo apt install --yes nodejs npm && \
npm install mongodb
app.js
const util = require('util');
const MongoClient = require('mongodb').MongoClient;
const DB_RS = '<replica_set_name>'
const DB_NAME = '<DB_name>'
const DB_HOSTS = ['<FQDN_of_MongoDB_host_1>:27018',
...,
'<FQDN_of_MongoDB_host_N>:27018']
const DB_USER = '<DB_username>'
const DB_PASS = '<DB_user_password>'
const CACERT = '/home/<home_directory>/.mongodb/root.crt'
const url = util.format('mongodb://%s:%s@%s/', DB_USER, DB_PASS, DB_HOSTS.join(','))
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
tls: true,
tlsCAFile: CACERT,
replicaSet: DB_RS,
authSource: DB_NAME
}
MongoClient.connect(url, options, function(err, conn) {
if (conn.isConnected()) {
const db = conn.db(DB_NAME)
console.log(db.databaseName)
}
conn.close()
})
app.js
const util = require('util');
const MongoClient = require('mongodb').MongoClient;
const DB_RS = '<replica_set_name>'
const DB_NAME = '<DB_name>'
const DB_HOSTS = ['<FQDN_of_MongoDB_host_1>:27018',
...
'<FQDN_of_MongoDB_host_N>:27018']
const DB_USER = '<DB_username>'
const DB_PASS = '<DB_user_password>'
const url = util.format('mongodb://%s:%s@%s/', DB_USER, DB_PASS, DB_HOSTS.join(','))
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
replicaSet: DB_RS,
authSource: DB_NAME
}
MongoClient.connect(url, options, function(err, conn) {
if (conn.isConnected()) {
const db = conn.db(DB_NAME)
console.log(db.databaseName)
}
conn.close()
})
To learn how to get a host FQDN, see this guide.
Connecting:
node app.js
PHP
Before connecting, install the dependencies:
sudo apt update && sudo apt install --yes php php-mongodb
connect.php
<?php
$DB_RS = '<replica_set_name>';
$DB_NAME = '<DB_name>';
$DB_HOSTS = '<FQDN_of_MongoDB_host_1>:27018,...,<FQDN_of_MongoDB_host_N>:27018';
$DB_USER = '<DB_username>';
$DB_PASS = '<DB_user_password>';
$CACERT = '/home/<home_directory>/.mongodb/root.crt';
$uri = sprintf(
'mongodb://%s:%s@%s/%s?replicaSet=%s',
$DB_USER,
$DB_PASS,
$DB_HOSTS,
$DB_NAME,
$DB_RS
);
$conn = new \MongoDB\Driver\Manager($uri, ["tls" => "true", "tlsCAFile" => $CACERT], []);
$command = new MongoDB\Driver\Command(array("ping" => 1));
try {
$cursor = $conn->executeCommand($DB_NAME, $command);
$response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception $ex) {
echo "$ex->getMessage()";
exit;
}
var_dump($response);
?>
connect.php
<?php
$DB_RS = '<replica_set_name>';
$DB_NAME = '<DB_name>';
$DB_HOSTS = '<FQDN_of_MongoDB_host_1>:27018,...,<FQDN_of_MongoDB_host_N>:27018';
$DB_USER = '<DB_username>';
$DB_PASS = '<DB_user_password>';
$uri = sprintf(
'mongodb://%s:%s@%s/%s?replicaSet=%s',
$DB_USER,
$DB_PASS,
$DB_HOSTS,
$DB_NAME,
$DB_RS
);
$conn = new \MongoDB\Driver\Manager($uri);
$command = new MongoDB\Driver\Command(array("ping" => 1));
try {
$cursor = $conn->executeCommand($DB_NAME, $command);
$response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception $ex) {
echo "$ex->getMessage()";
exit;
}
var_dump($response);
?>
To learn how to get a host FQDN, see this guide.
Connecting:
php connect.php
PowerShell
Before connecting, install the MongoDB Shell utility
mongosh.exe --norc `
--host '<FQDN_of_MongoDB_host_1>:27018,...,<FQDN_of_MongoDB_host_N>:27018' `
--tls `
--tlsCAFile $HOME\.mongodb\root.crt `
--username <DB_username> `
--password <DB_user_password> `
<DB_name>
mongosh.exe --norc `
--host '<FQDN_of_MongoDB_host_1>:27018,...,<FQDN_of_MongoDB_host_N>:27018' `
--username <DB_username> `
--password <DB_user_password> `
<DB_name>
To learn how to get a host FQDN, see this guide.
After connecting, run the db
command.
Python
Before connecting, install the dependencies:
sudo apt update && sudo apt install --yes python3 python3-pip && \
pip3 install pyMongo
To find out the name of a replica set, connect to the database via MongoDB Shell and run this command:
rs.status().set
connect.py
import ssl
import pymongo
from urllib.parse import quote_plus as quote
CACERT = '/home/<home_directory>/.mongodb/root.crt'
DB_RS = '<replica_set_name>'
DB_NAME = '<DB_name>'
DB_HOSTS =','.join([
'<FQDN_of_MongoDB_host_1>:27018',
...,
'<FQDN_of_MongoDB_host_N>:27018'
])
DB_USER = '<DB_username>'
DB_PASS = '<DB_user_password>'
url = 'mongodb://{user}:{pw}@{hosts}/?replicaSet={rs}&authSource={auth_src}'.format(
user=quote(DB_USER),
pw=quote(DB_PASS),
rs=DB_RS,
hosts=DB_HOSTS,
auth_src=DB_NAME)
conn = pymongo.MongoClient(
url,
tls=True,
tlsCAFile=CACERT)
db = conn[DB_NAME]
print(db.name)
conn.close()
connect.py
import ssl
import pymongo
from urllib.parse import quote_plus as quote
DB_RS = '<replica_set_name>'
DB_NAME = '<DB_name>'
DB_HOSTS =','.join([
'<FQDN_of_MongoDB_host_1>:27018',
...,
'<FQDN_of_MongoDB_host_N>:27018'
])
DB_USER = '<DB_username>'
DB_PASS = '<DB_user_password>'
url = 'mongodb://{user}:{pw}@{hosts}/?replicaSet={rs}&authSource={auth_src}'.format(
user=quote(DB_USER),
pw=quote(DB_PASS),
rs=DB_RS,
hosts=DB_HOSTS,
auth_src=DB_NAME)
conn = pymongo.MongoClient(url)
db = conn[DB_NAME]
print(db.name)
conn.close()
To learn how to get a host FQDN, see this guide.
Connecting:
python3 connect.py