All Products
Search
Document Center

ApsaraDB for MongoDB:SSL connection sample code for MongoDB drivers

Last Updated:Mar 28, 2026

Use these code samples to establish an SSL connection from your application to ApsaraDB for MongoDB. Each sample configures the driver to verify the server's certificate using a certification authority (CA) certificate while skipping hostname verification—a requirement for ApsaraDB for MongoDB SSL connections.

For information about enabling SSL on your instance, see Configure SSL encryption for an instance.

Prerequisites

Before you begin, ensure that you have:

  • SSL enabled on your ApsaraDB for MongoDB instance

  • The CA certificate file (ca.pem) downloaded from the instance SSL configuration page

  • The connection string for your instance (available on the instance details page)

How hostname verification works in these samples

ApsaraDB for MongoDB SSL connections require the client to verify the server certificate against a CA, but the server's hostnames do not match the certificate's Common Name (CN). All samples in this topic disable hostname verification to accommodate this.

Warning

Disabling hostname verification reduces connection security. Use this configuration only with ApsaraDB for MongoDB instances, and always verify the server certificate using the CA file.

The table below summarizes the key SSL parameters for each driver.

DriverEnable SSLSpecify CADisable hostname verification
Node.jsssl=true in URIsslCAcheckServerIdentity: false
PHPssl: true in $uriOptionsca_file in $driverOptionsallow_invalid_hostname: true
JavasslEnabled(true)keytool + JVM propertiessslInvalidHostNameAllowed(true)
Pythonssl=Truessl_ca_certsssl_match_hostname=False
Cssl=true in URIca_file in mongoc_ssl_opt_tallow_invalid_hostname = false
C++ssl=true in URIca_file in mongocxx::options::sslNot supported
Scalaenabled(true) in SslSettingskeytool + JVM propertiesinvalidHostNameAllowed(true)
Golangssl=true in URIRootCAs in tls.ConfigInsecureSkipVerify: true
.NET CoreUseTls = trueX509Certificate in SslSettingsAllowInsecureTls = true

Node.js

Driver reference: MongoDB Node.js Driver

Append ?ssl=true to the connection URI, set sslCA to the path of your CA certificate file, and set checkServerIdentity to false to skip hostname verification.

var MongoClient = require('mongodb').MongoClient,
  f = require('util').format,
  fs = require('fs');

// Load the CA certificate
var ca = [fs.readFileSync(__dirname + "/path/to/ca.pem")];

MongoClient.connect("mongodb://host01:27017,host02:27017,host03:27017/?replicaSet=myreplset&ssl=true", {
  server: {
    sslValidate: true,
    checkServerIdentity: false,  // Skip hostname verification
    sslCA: ca
  }
}, function(err, db) {
  db.close();
});

PHP

Driver reference: MongoDB PHP Driver

Create a MongoDB\Client instance using the constructor:

function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [], array $driverOptions = [])

In $uriOptions, set ssl to true. In $driverOptions, set ca_file to the path of your CA certificate file and set allow_invalid_hostname to true to skip hostname verification.

<?php
$client = new MongoDB\Client(
    'mongodb://host01:27017,host02:27017,host03:27017',
    [
        'ssl' => true,
        'replicaSet' => 'myReplicaSet'
    ],
    [
        "ca_file" => "/path/to/ca.pem",
        "allow_invalid_hostname" => true
    ]
);
?>

Java

Driver reference: MongoDB Java Driver

Java SSL configuration requires two steps: configure the driver options, then register the CA certificate with the Java Virtual Machine (JVM).

Step 1: Configure driver options

In MongoClientOptions, set sslEnabled to true and sslInvalidHostNameAllowed to true to skip hostname verification.

import com.mongodb.MongoClientURI;
import com.mongodb.MongoClientOptions;

MongoClientOptions options = MongoClientOptions.builder()
    .sslEnabled(true)
    .sslInvalidHostNameAllowed(true)
    .build();
MongoClient client = new MongoClient(
    "mongodb://host01:27017,host02:27017,host03:27017/?replicaSet=myreplset",
    options
);

Step 2: Import the CA certificate into the JVM trust store

Run the following keytool command to import the CA certificate:

keytool -importcert -trustcacerts -file <path to certificate authority file> \
        -keystore <path to trust store> -storepass <password>

Then set the JVM system properties to point to the trust store:

System.setProperty("javax.net.ssl.trustStore", "/trust/mongoStore.ts");
System.setProperty("javax.net.ssl.trustStorePassword", "StorePass");

Python

Driver reference: MongoDB Python Driver (PyMongo)

Set ssl=True, set ssl_ca_certs to the path of your CA certificate file, and set ssl_match_hostname=False to skip hostname verification.

import ssl
from pymongo import MongoClient

uri = "mongodb://host01:27017,host02:27017,host03:27017/?replicaSet=myreplset"
client = MongoClient(uri,
                     ssl=True,
                     ssl_ca_certs='ca.pem',
                     ssl_match_hostname=False)

C

Driver reference: MongoDB C Driver

Append ?ssl=true to the connection URI. Use mongoc_ssl_opt_t to set the CA certificate path and disable hostname verification.

mongoc_client_t *client = NULL;
client = mongoc_client_new(
    "mongodb://host01:27017,host02:27017,host03:27017/?replicaSet=myreplset&ssl=true");

const mongoc_ssl_opt_t *ssl_default = mongoc_ssl_opt_get_default();
mongoc_ssl_opt_t ssl_opts = { 0 };

/* Copy default SSL options, then override as needed. */
memcpy(&ssl_opts, ssl_default, sizeof ssl_opts);
ssl_opts.ca_file = "/path/to/ca.pem";
ssl_opts.allow_invalid_hostname = false;  // Skip hostname verification
mongoc_client_set_ssl_opts(client, &ssl_opts);

C++

Driver reference: MongoDB C++ Driver

Append ?ssl=true to the connection URI and use mongocxx::options::ssl to set the CA certificate path.

Note

The MongoDB C++ driver does not support disabling hostname verification.

#include <mongocxx/client.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/options/client.hpp>
#include <mongocxx/options/ssl.hpp>

mongocxx::options::client client_options;
mongocxx::options::ssl ssl_options;

// Set the CA certificate file
ssl_options.ca_file("/path/to/ca.pem");
client_options.ssl_opts(ssl_options);

auto client = mongocxx::client{
    uri{"mongodb://host01:27017,host02:27017,host03:27017/?replicaSet=myreplset&ssl=true"},
    client_options};

Scala

Driver reference: MongoDB Scala Driver

The Scala driver uses Netty for SSL. Configure SslSettings in MongoClientSettings to enable SSL and skip hostname verification.

Step 1: Configure driver settings

import org.mongodb.scala.connection.{NettyStreamFactoryFactory, SslSettings}

MongoClientSettings.builder()
    .sslSettings(SslSettings.builder()
                             .enabled(true)
                             .invalidHostNameAllowed(true)  // Skip hostname verification
                             .build())
    .streamFactoryFactory(NettyStreamFactoryFactory())
    .build()

val client: MongoClient = MongoClient(
    "mongodb://host01:27017,host02:27017,host03:27017/?replicaSet=myreplset")

Step 2: Import the CA certificate into the JVM trust store

The process is the same as for the Java driver. Run:

keytool -importcert -trustcacerts -file <path to certificate authority file> \
        -keystore <path to trust store> -storepass <password>

Then set the JVM system properties:

System.setProperty("javax.net.ssl.trustStore", "/trust/mongoStore.ts");
System.setProperty("javax.net.ssl.trustStorePassword", "StorePass");

Golang

Driver references: MongoDB Go Driver and Go crypto/tls package

Load the CA certificate into a tls.Config struct, set InsecureSkipVerify to true to skip hostname verification, then pass the config to the client options.

package main

import (
    "context"
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
    "go.mongodb.org/mongo-driver/mongo/writeconcern"
    "io/ioutil"
    "log"
)

func main() {
    // Load the CA certificate
    var filename = "ca.pem"
    rootPEM, err := ioutil.ReadFile(filename)
    roots := x509.NewCertPool()
    if ok := roots.AppendCertsFromPEM([]byte(rootPEM)); !ok {
        fmt.Printf("get certs from %s fail!\n", filename)
        return
    }

    tlsConfig := &tls.Config{
        RootCAs:            roots,
        InsecureSkipVerify: true,  // Skip hostname verification
    }

    // Connect to the instance
    // Replace the URI placeholders with your actual instance endpoints and credentials.
    clientOpts := options.Client().ApplyURI(
        "mongodb://test:****@dds-bp*******1.mongodb.rds.aliyuncs.com:3717," +
        "dds-bp*******2.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-XXXXX&ssl=true")
    clientOpts.SetReadPreference(readpref.Secondary())
    clientOpts.SetWriteConcern(writeconcern.New(
        writeconcern.WMajority(),
        writeconcern.J(true),
        writeconcern.WTimeout(1000)))
    clientOpts.SetTLSConfig(tlsConfig)

    client, err := mongo.Connect(context.TODO(), clientOpts)
    if err != nil {
        fmt.Println("connect failed!")
        log.Fatal(err)
        return
    }
    fmt.Println("connect successful!")

    defer func() {
        if err = client.Disconnect(context.TODO()); err != nil {
            fmt.Println("disconnect failed!")
            log.Fatal(err)
        }
        fmt.Println("disconnect successful!")
    }()

    // Verify the connection
    if err = client.Ping(context.TODO(), nil); err != nil {
        fmt.Println("ping failed!")
        log.Fatal(err)
        return
    }
    fmt.Println("ping successful!")

    // Example: insert and retrieve a document
    collection := client.Database("baz").Collection("qux")
    res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
    if err != nil {
        fmt.Println("insert result failed!")
        log.Fatal(err)
        return
    }
    id := res.InsertedID
    fmt.Println("Id: ", id)
    fmt.Printf("insert result: %v\n", res)

    result := bson.M{}
    filter := bson.D{{"_id", res.InsertedID}}
    if err := collection.FindOne(context.Background(), filter).Decode(&result); err != nil {
        fmt.Println("find failed!")
        log.Fatal(err)
        return
    }
    fmt.Printf("result: %v\n", result)
}

.NET Core

Driver reference: MongoDB C# Driver

Step 1: Set up the project

Create a new console project and install the MongoDB driver:

dotnet new console -o MongoDB
cd MongoDB
dotnet add package mongocsharpdriver --version 2.11.5

Step 2: Connect with SSL

Configure MongoClientSettings with UseTls = true, AllowInsecureTls = true (to skip hostname verification), and a SslSettings object that includes your CA certificate.

using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using MongoDB.Bson;
using MongoDB.Driver;

namespace dotnetCase
{
    class Program
    {
        static void Main(string[] args)
        {
            // Replace these values with your instance connection details.
            const string host1 = "dds-***********-pub.mongodb.rds.aliyuncs.com";
            const int port1 = 3717;
            const string host2 = "dds-***********-pub.mongodb.rds.aliyuncs.com";
            const int port2 = 3717;
            const string replicaSetName = "mgset-********"; // Remove for sharded cluster instances.
            const string admin = "admin";
            const string userName = "test";
            const string passwd = "********";

            try
            {
                // Configure the connection
                MongoClientSettings settings = new MongoClientSettings();
                List<MongoServerAddress> servers = new List<MongoServerAddress>();
                servers.Add(new MongoServerAddress(host1, port1));
                servers.Add(new MongoServerAddress(host2, port2));
                settings.Servers = servers;
                settings.ReplicaSetName = replicaSetName; // Remove for sharded cluster instances.
                settings.ConnectTimeout = new TimeSpan(0, 0, 0, 3, 0); // 3-second timeout

                // Set credentials
                MongoCredential credentials = MongoCredential.CreateCredential(admin, userName, passwd);
                settings.Credential = credentials;

                // Configure SSL
                SslSettings sslSettings = new SslSettings {
                    ClientCertificates = new[] { new X509Certificate("ca.pem") },
                };
                settings.UseTls = true;
                settings.AllowInsecureTls = true;  // Skip hostname verification
                settings.SslSettings = sslSettings;

                MongoClient client = new MongoClient(settings);
            }
            catch (Exception e)
            {
                Console.WriteLine("connection failed: " + e.Message);
            }
        }
    }
}

What's next