All Products
Search
Document Center

ApsaraDB for MongoDB:Connect to a replica set instance

Last Updated:Mar 28, 2026

ApsaraDB for MongoDB replica set instances expose six endpoint types — from high-availability connection strings to individual node addresses. This topic explains each type, shows the connection string format, and walks you through retrieving your endpoint and connecting to the database.

Prerequisites

Before you begin, ensure that you have:

  • An ApsaraDB for MongoDB replica set instance in a Running state

  • A database account and password (the default account is root; create a dedicated account for production use)

  • Network access to the instance — the client host is in the instance whitelist and can reach the instance over a virtual private cloud (VPC) or the public network

  • (Public network only) A public endpoint applied and enabled

Choose an endpoint type

For production applications, use a ConnectionStringURI SRV or ConnectionStringURI address. Both provide load balancing and automatic failover. The SRV address is recommended because the client automatically discovers all replica set members and adapts to topology changes — when you add or remove nodes, no connection-string update is required.

Single-node addresses (Primary, Secondary, ReadOnly) are for ad-hoc access and administrative tasks only.

Endpoint typeWhen to use
ConnectionStringURI SRV (recommended)Production applications. The client automatically discovers all replica set members, distributes read requests, and fails over without connection-string changes when nodes are added or removed.
ConnectionStringURIProduction applications when SRV is unavailable. Contains all node addresses and supports readPreference for read/write splitting. Must be updated manually when the cluster topology changes.
ReadOnly ConnectionStringURIApplications that only read data and the instance has read-only nodes. Routes all reads to read-only nodes; write requests go to the primary node.
Primary addressAd-hoc access or administrative tasks. Do not use in production — the address changes after a primary/secondary switchover.
Secondary addressRead-only ad-hoc access. Do not use in production — the node may be promoted to primary after a switchover, which would cause write requests to fail.
ReadOnly addressDirect access to a specific read-only node. Only available when the instance has read-only nodes.
The Primary, Secondary, and ReadOnly addresses are single-node endpoints. When a primary/secondary switchover occurs, node roles change, which can disrupt applications connected to these addresses.

Retrieve the database endpoint

  1. Go to the Replica Set Instances page. Select a resource group and region, then click the ID of the target instance.

  2. In the left navigation pane, click Database Connections. The page shows all available endpoints for the instance, grouped by network type (VPC and public network).

  3. (SRV address only) The console does not display SRV addresses by default. To get one, click Apply for Private SRV Endpoint or Apply for Public SRV Endpoint. Before applying for a public SRV address, enable a public endpoint for the instance first.

SRV addresses are available only for instances that use disks.

Connection string formats

ConnectionStringURI SRV address

mongodb+srv://<username>:<password>@<srv-host>/<database>?[authSource=<authenticationDatabase>][&readPreference=<readPreference_value>][&readPreferenceTags=<readonly_Tags>]<other_options>

Parameters:

ParameterDescription
mongodb+srv://Indicates that DNS SRV records are used for service discovery.
<username>The database account name.
<password>The database account password.
<srv-host>The hostname of the SRV endpoint.
<database>The database to access. Default: admin.
authSource=<authenticationDatabase> (optional)The database where the account is defined. The TXT record for ApsaraDB for MongoDB SRV addresses sets authSource=admin by default, which overrides the <database> value. To authenticate against a different database, explicitly set authSource=<authenticationDatabase>. For more information, see the official MongoDB documentation.
readPreference (optional)Controls which node receives read requests. See Read request routing below.
readPreferenceTags (optional)Filters nodes by tag. Used with readPreference. See Read request routing below.
<other_options>Additional connection options. SSL is enabled by default for SRV connections. Add ssl=false to disable it. For all options, see the official MongoDB documentation.
SRV addresses or node auto-discovery require a minimum driver version: pymongo >= 3.9.0, mongo-java-driver >= 3.10.0, mongodb-go-driver >= 1.1.0, MongoDB Node.js driver >= 3.3.0, mongo-cxx-driver >= 3.8.

Example:

mongodb+srv://test:****@dds-bp19215393a0****-srv.mongodb.nosql.aliyuncs.com/admin?ssl=false

ConnectionStringURI address

mongodb://<username>:<password>@<host1>:<port1>,<host2>:<port2>,...,<hostN>:<portN>/<database>?replicaSet=<replicaSet_value>[&authSource=<authenticationDatabase>][&readPreference=<readPreference_value>][&readPreferenceTags=<readonly_Tags>]

Parameters:

ParameterDescription
<username>The database account name. Default: root.
<password>The database account password.
<host>The domain name of a primary, secondary, or read-only node. The string lists all nodes.
<port>The port of the corresponding node.
<database>The database to access. Default: admin.
replicaSet=<replicaSet_value>Routes read requests to all nodes in the replica set. <replicaSet_value> is the unique ID of the high-availability endpoint.
authSource=<authenticationDatabase> (optional)The database where the account is defined. If omitted, <database> is used as the authentication database.
readPreference (optional)Controls which node receives read requests. See Read request routing below.
readPreferenceTags (optional)Filters nodes by tag. Used with readPreference. See Read request routing below.
Important

When you add or remove nodes from the instance, update this connection string to include or remove the corresponding node addresses.

Example:

mongodb://root:****@dds-bp19f409d7512****.mongodb.rds.aliyuncs.com:3717,dds-bp19f409d7512****.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-6108****

ReadOnly ConnectionStringURI address

mongodb://<username>:<password>@<host1>:<port1>,<host2>:<port2>,...,<hostN>:<portN>/<database>?readPreference=secondary&readPreferenceTags=role:readonly&replicaSet=<replicaSet_value>[&authSource=<authenticationDatabase>]

Parameters:

ParameterDescription
<username>The database account name. Default: root.
<password>The database account password.
<host>The Domain Name of a read-only node.
<port>The Port of the read-only node.
<database>The database to access. Default: admin.
readPreference=secondary&readPreferenceTags=role:readonlyRoutes read requests to read-only nodes. The readPreferenceTags value is fixed at role:readonly and cannot be changed.
replicaSet=<replicaSet_value>Routes read requests to all nodes in the replica set. <replicaSet_value> is the unique ID of the high-availability endpoint.
authSource=<authenticationDatabase> (optional)The database where the account is defined. If omitted, <database> is used as the authentication database.
If a read-only node fails, read requests automatically switch to another read-only node. If all read-only nodes fail, the connection returns an error.

Example:

mongodb://root:****@dds-bp19f409d7512****.mongodb.rds.aliyuncs.com:3717/admin?readPreference=secondary&readPreferenceTags=role:readonly&replicaSet=mgset-6108****

Primary, secondary, and ReadOnly addresses

All three single-node address types use the same format:

mongodb://<username>:<password>@<host>:<port>/<database>?[directConnection=true]
ParameterDescription
<username>The database account name.
<password>The database account password.
<host>The Domain Name of the node.
<port>The Port of the node.
<database>The database to access. Default: admin.
directConnection=true (optional)Sends all requests only to the specified node, bypassing service discovery. Without this parameter, the client may forward requests to other nodes.

Behavior by node type:

Node typedirectConnection=truedirectConnection=false (default)
PrimaryBoth read and write go to the primary node.Read requests may be forwarded to other nodes.
SecondaryWrite requests are rejected.Write requests are forwarded to the primary node.
ReadOnlyWrite requests are rejected.Write requests are forwarded to the primary node.

Example:

mongodb://root:****@dds-bp19f409d7512****.mongodb.rds.aliyuncs.com:3717/admin?directConnection=true

Network types

Network typeDescription
VPC (default)A virtual private cloud (VPC) provides an isolated network with higher security and performance. All instances have VPC endpoints by default.
Classic networkA non-isolated network protected by security groups or whitelists. New instances no longer support the classic network. See [Notice] New ApsaraDB for MongoDB instances no longer support the classic network.
Public networkConnecting over the public network is inherently less secure. Public endpoints are not enabled by default — apply for a public endpoint before connecting.

Read request routing

The readPreference and readPreferenceTags parameters in the ConnectionStringURI SRV and ConnectionStringURI addresses control which node handles read requests.

readPreference values

ValueBehavior
primaryAll reads go to the primary node.
primaryPreferredReads go to the primary node first. If the primary fails, reads fall back to secondary and read-only nodes.
secondaryReads go to secondary and read-only nodes only. If all fail, reads fail — no fallback to primary.
secondaryPreferredReads go to secondary and read-only nodes first. If all fail, reads fall back to the primary node.

readPreferenceTags values

Use readPreferenceTags with readPreference to target a specific subset of nodes. This parameter is not compatible with readPreference=primary.

Tag valueTarget nodesRequirement
role:electableSecondary nodes (eligible to be elected primary)Disk instances only
role:readonlyRead-only nodes

Routing policy reference

Combine readPreference and readPreferenceTags to match your read consistency and failover requirements.

PolicyTarget nodeParameters
Fallback to primary allowedPrimary firstreadPreference=primaryPreferred
Secondary and read-only firstreadPreference=secondaryPreferred
Secondary first (falls back to primary if secondary fails)readPreference=secondaryPreferred&readPreferenceTags=role:electable
Read-only first (falls back to primary if read-only fails)readPreference=secondaryPreferred&readPreferenceTags=role:readonly
No fallback to primarySecondary and read-onlyreadPreference=secondary
Secondary only (fails if all secondary nodes fail)readPreference=secondary&readPreferenceTags=role:electable
Read-only (fails if all read-only nodes fail)readPreference=secondary&readPreferenceTags=role:readonly
When reads are distributed across secondary and read-only nodes, load may be uneven. Use readPreferenceTags to target a specific node type.

Read/write splitting example

For applications that need read-after-write consistency on some operations, create separate connection clients — one pointing to the primary for writes, one using secondaryPreferred for reads:

import pymongo

# Write client: sends all requests to the primary node
client_primary = pymongo.MongoClient(
    "mongodb://root:****@dds-bp19f409d7512****.mongodb.rds.aliyuncs.com:3717"
    "/admin?replicaSet=mgset-6108****&readPreference=primary"
)

# Read client: sends reads to secondary and read-only nodes first,
# falls back to primary if all secondary nodes fail
client_reads = pymongo.MongoClient(
    "mongodb://root:****@dds-bp19f409d7512****.mongodb.rds.aliyuncs.com:3717"
    "/admin?replicaSet=mgset-6108****&readPreference=secondaryPreferred"
)

db_write = client_primary["mydb"]
db_read = client_reads["mydb"]

# Use db_write for operations that require read-after-write consistency
db_write["orders"].insert_one({"order_id": "12345", "status": "pending"})

# Use db_read for general read queries
results = list(db_read["products"].find({"category": "electronics"}))

Log in to the database

After retrieving your endpoint, connect using one of the following methods:

Important

Do not use the root account in production. Create a dedicated database account with only the permissions it needs. If you have forgotten the password, reset it before connecting.

Common connection scenarios

FAQ

Why does the client send requests to other nodes in the instance when I connect using a single-node endpoint?

This is normal and expected behavior. It is caused by service discovery, a core feature of the MongoDB client that implements high availability (HA). This feature allows the client to automatically adapt to cluster topology changes, such as a primary node breakdown, to ensure service continuity. You can append directConnection=true to the connection string to specify that requests are sent only to the current endpoint. For more information, see directConnection.

What's next