Yandex Cloud
Search
Discuss with expertTry it for free
  • Customer Stories
  • Documentation
  • Blog
  • All Services
    • Cloud Interconnect
    • Cloud Backup
    • Cloud Registry
    • Yandex AI Studio
    • Compute Cloud
    • Object Storage
    • Managed Service for Kubernetes®
    • Yandex BareMetal
    • Smart Web Security
    • Security Deck
    • Managed Service for PostgreSQL
    • Managed Service for ClickHouse®
    • Monium
    • Cloud CDN
    • Network Load Balancer
    • Virtual Private Cloud
    • Cloud DNS
    • Application Load Balancer
    • Yandex Cloud Video
    • Stackland
    • Yandex Cloud Router
    • Yandex Managed Service for Trino
    • Managed Service for MySQL®
    • Managed Service for Valkey™
    • Managed Service for Apache Spark™
    • Yandex StoreDoc
    • Managed Service for OpenSearch
    • Managed Service for Apache Kafka®
    • Data Transfer
    • Yandex MPP Analytics Engine for PostgreSQL
    • Yandex Managed Service for Apache Airflow®
    • Data Processing
    • Yandex MetaData Hub
    • Managed Service for YDB
    • Managed Service for Sharded PostgreSQL
    • Managed Service for YTsaurus
    • Yandex WebSQL
    • DataLens
    • Yandex Search API
    • SpeechSense
    • SpeechKit
    • DataSphere
    • Vision OCR
    • Translate
    • Yandex Identity Hub
    • Key Management Service
    • Certificate Manager
    • Yandex Lockbox
    • Audit Trails
    • SmartCaptcha
    • Cloud Desktop
    • SourceCraft Code Assistant
    • Container Registry
    • Managed Service for GitLab
    • Managed Service for Prometheus®
    • Cloud Functions
    • API Gateway
    • Yandex Cloud Postbox
    • Message Queue
    • Serverless Integrations
    • IoT Core
    • Data Streams
    • Serverless Containers
    • Cloud Notification Service
    • Yandex Query
    • Identity and Access Management
    • Yandex Cloud Console
    • Resource Manager
    • Yandex Cloud Billing
    • Yandex Cloud Quota Manager
    • Cloud Apps
  • System Status
  • Marketplace
    • Featured
    • Infrastructure & Network
    • Data Platform
    • AI for business
    • Security
    • DevOps tools
    • Serverless
    • Monitoring & Resources
  • All Solutions
    • By industry
    • By use case
    • Economics and Pricing
    • Security
    • Technical Support
    • Start testing with double trial credits
    • Cloud credits to scale your IT product
    • Gateway to Russia
    • Cloud for Startups
    • Center for Technologies and Society
    • Yandex Cloud Partner program
    • Price calculator
    • Pricing plans
  • Customer Stories
  • Documentation
  • Blog
© 2026 Direct Cursus Technology L.L.C.
Yandex StoreDoc
  • Getting started
    • All guides
      • Pre-configuration
      • Connecting from applications
        • Overview
        • Connection examples for non-sharded clusters
        • Connection examples for sharded clusters
  • Access management
  • Pricing policy
  • Terraform reference
  • Monitoring metrics
  • Audit Trails events
  • Public materials
  • Release notes

In this article:

  • Go
  • Java
  • Node.js
  • PHP
  • Python
  1. Step-by-step guides
  2. Connection
  3. Code examples
  4. Connection examples for sharded clusters

Code examples for connecting to a sharded Yandex StoreDoc cluster

Written by
Yandex Cloud
Updated at July 6, 2026
View in Markdown
  • Go
  • Java
  • Node.js
  • PHP
  • Python

GoGo

Before connecting, install the following dependencies:

sudo apt update && sudo apt install --yes golang git && \
go get go.mongodb.org/mongo-driver/mongo
Connecting with SSL
Connecting without SSL

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_NAME = "<DB_name>"
      DB_HOSTS := []string {"<MONGOINFRA_or_MONGOS_host_1_FQDN>:27017",
                            ...,
                            "<MONGOINFRA_or_MONGOS_host_N_FQDN>:27017"}
      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?tls=true&tlsCaFile=%s",
              DB_USER,
              DB_PASS,
              strings.Join(DB_HOSTS, ","),
              DB_NAME,
              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_NAME = "<DB_name>"
      DB_HOSTS := []string {"<MONGOINFRA_or_MONGOS_host_1_FQDN>:27017",
                            ...,
                            "<MONGOINFRA_or_MONGOS_host_N_FQDN>:27017"}
      const DB_USER = "<DB_username>"
      const DB_PASS = "<DB_user_password>"

      url := fmt.Sprintf("mongodb://%s:%s@%s/%s?tls=false",
              DB_USER,
              DB_PASS,
              strings.Join(DB_HOSTS, ","),
              DB_NAME)

      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

JavaJava

Before connecting:

  1. Install the dependencies:

    sudo apt update && sudo apt install --yes default-jdk maven
    
  2. Add the SSL certificate to the Java trusted certificate store (Java Key Store) so that the Yandex StoreDoc driver can use this certificate for secure connections to the cluster hosts. Set a password in the -storepass parameter for additional storage protection:

    cd ~/.mongodb && \
    sudo keytool -importcert \
                 -alias YandexCA -file root.crt \
                 -keystore ssl -storepass <password> \
                 --noprompt
    

    Where storepass is your certificate store password, a minimum of 6 characters.

  3. Create a directory for the Maven project:

    cd ~/ && \
    mkdir --parents project/src/java/com/example && \
    cd ~/project
    
  4. 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>
    

    Current versions of Maven dependencies:

    • mongodb-driver-sync
    • slf4j-simple
Connecting with SSL
Connecting without SSL

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 = 27017;

    List DB_HOSTS = new ArrayList<ServerAddress>();
    DB_HOSTS.add(new ServerAddress("<MONGOINFRA_or_MONGOS_host_1_FQDN>", DB_PORT));
    ...
    DB_HOSTS.add(new ServerAddress("<MONGOINFRA_or_MONGOS_host_N_FQDN>", 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 = 27017;

    List DB_HOSTS = new ArrayList<ServerAddress>();
    DB_HOSTS.add(new ServerAddress("<MONGOINFRA_or_MONGOS_host_1_FQDN>", DB_PORT));
    ...
    DB_HOSTS.add(new ServerAddress("<MONGOINFRA_or_MONGOS_host_N_FQDN>", 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.jsNode.js

Before connecting, install the required dependencies:

sudo apt update && sudo apt install --yes nodejs npm && \
npm install mongodb
Connecting with SSL
Connecting without SSL

app.js

const util = require('util');
const MongoClient = require('mongodb').MongoClient;

const DB_NAME = '<DB_name>'
const DB_HOSTS = ['<MONGOINFRA_or_MONGOS_host_1_FQDN>:27017',
                  ...,
                  '<MONGOINFRA_or_MONGOS_host_N_FQDN>:27017']
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,
  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_NAME = '<DB_name>'
const DB_HOSTS = ['<MONGOINFRA_or_MONGOS_host_1_FQDN>:27018',
                  ...,
                  '<MONGOINFRA_or_MONGOS_host_N_FQDN>: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,
  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

PHPPHP

Before connecting, install the required dependencies:

sudo apt update && sudo apt install --yes php php-mongodb
Connecting with SSL
Connecting without SSL

connect.php

<?php
  $DB_NAME  = '<DB_name>';
  $DB_HOSTS = '<MONGOINFRA_or_MONGOS_host_1_FQDN>:27017,...,<MONGOINFRA_or_MONGOS_host_N_FQDN>:27017';
  $DB_USER  = '<DB_username>';
  $DB_PASS  = '<DB_user_password>';
  $CACERT   = '/home/<home_directory>/.mongodb/root.crt';

  $uri = sprintf(
      'mongodb://%s:%s@%s/%s',
      $DB_USER,
      $DB_PASS,
      $DB_HOSTS,
      $DB_NAME
  );

  $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_NAME  = '<DB_name>';
  $DB_HOSTS = '<MONGOINFRA_or_MONGOS_host_1_FQDN>:27017,...,<MONGOINFRA_or_MONGOS_host_N_FQDN>:27017';
  $DB_USER  = '<DB_username>';
  $DB_PASS  = '<DB_user_password>';

  $uri = sprintf(
      'mongodb://%s:%s@%s/%s',
      $DB_USER,
      $DB_PASS,
      $DB_HOSTS,
      $DB_NAME
  );

  $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

PythonPython

Before connecting, install the required dependencies:

sudo apt update && sudo apt install --yes python3 python3-pip && \
pip3 install pyMongo
Connecting with SSL
Connecting without SSL

connect.py

import ssl
import pymongo
from urllib.parse import quote_plus as quote

CACERT = '/home/<home_directory>/.mongodb/root.crt'
DB_NAME = '<DB_name>'
DB_HOSTS =','.join([
      '<MONGOINFRA_or_MONGOS_host_1_FQDN>:27017',
      ...,
      '<MONGOINFRA_or_MONGOS_host_N_FQDN>:27017'
    ])
DB_USER = '<DB_username>'
DB_PASS = '<DB_user_password>'

url = 'mongodb://{user}:{pw}@{hosts}/?authSource={auth_src}'.format(
          user=quote(DB_USER),
          pw=quote(DB_PASS),
          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_NAME = '<DB_name>'
DB_HOSTS =','.join([
      '<MONGOINFRA_or_MONGOS_host_1_FQDN>:27017',
      ...,
      '<MONGOINFRA_or_MONGOS_host_N_FQDN>:27017'
    ])
DB_USER = '<DB_username>'
DB_PASS = '<DB_user_password>'

url = 'mongodb://{user}:{pw}@{hosts}/?authSource={auth_src}'.format(
          user=quote(DB_USER),
          pw=quote(DB_PASS),
          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

Was the article helpful?

Previous
Connection examples for non-sharded clusters
Next
SQL queries in Yandex WebSQL
© 2026 Direct Cursus Technology L.L.C.