All Products
Search
Document Center

ApsaraDB for MongoDB:Connection and network

Last Updated:Jan 06, 2026

This topic helps you resolve common connection issues with ApsaraDB for MongoDB instances. We recommend checking the Common errors section first for a quick solution. If your error isn't listed, follow the Troubleshooting steps for a systematic diagnosis.

Troubleshooting steps

Step 1: Check network connectivity

Troubleshooting method

Use the following commands to test network connectivity.

  • ping <domain name>, for example, ping dds-xxxx.mongodb.rds.aliyuncs.com

    image

    The figure shows a successful network connection between the client and the MongoDB instance.

  • telnet <domain name> <port number>, for example, telnet dds-xxxx.mongodb.rds.aliyuncs.com 3717

    测试端口The figure shows that the domain name is resolved and that communication is possible over port 3717.

Checklist

If the network test fails, use the following checklist to identify and resolve the issue.

Check the instance status: Ensure the instance is in the Running state.

Check the whitelist settings: Ensure the client IP address is added to the whitelist.

  • How to check:

    Temporarily add 0.0.0.0/0 to the database whitelist. If the connection succeeds, the problem is an incorrect IP address configuration.

    Important

    Using 0.0.0.0/0 creates a severe security risk by exposing your instance to the entire internet. Use this for diagnostic purposes only and replace it with the correct client IP address immediately after testing.

  • Solution:

    Add the correct client IP address to the instance's whitelist. To find your client's public IP address, see FAQ.

Check the network environment and instance endpoint: Ensure you are using the correct endpoint for your network type.

ApsaraDB for MongoDB supports private and public network connections. Different network environments require different endpoints.

You can find the endpoints in the ApsaraDB for MongoDB console on the Database Connection page.

Step 2: Authorization and identity verification

Check the account credentials: Ensure the password is correct and special characters are properly escaped.

  • Confirm that the provided account name and password are correct.

  • Change the password. For more information about how to change the password, see Reset a password.

    If you change the password after you connect to the ApsaraDB for MongoDB instance using DMS, go to the DMS console, right-click the target instance, and then select Edit to log on again.

  • Special characters. When you connect to an ApsaraDB for MongoDB instance using Mongo Shell or program code, you must escape special characters if the password in the connection string contains them. These include characters such as !@#$%^&*()_+=. For more information, see How do I resolve connection failures caused by special characters in the account or password of a connection string?.

Check the authentication database: Ensure the account is authenticated against the correct database.

Check the instance endpoint: For write operations on replica set instances, ensure you are using the ConnectionString URI endpoint.

  • Symptom: The instance suddenly becomes inaccessible without any changes to the endpoint.

  • Cause: Only the primary node can perform write operations. If your application previously connected via the primary node address, after a replica set failover, the actual connected node may become a secondary node, causing write operations to fail.

  • Solution:

    • It is recommended that applications in production environments connect to the database using the ConnectionString URI address. In case of node failure, the application's read and write operations will not be affected by primary-secondary failover. For details on connection addresses, see:

    • Manually switch node roles. Switch the node that corresponds to the single-node endpoint used by your service to the primary node.

    Design a reconnection mechanism and exception handling for your application. This ensures that your application can automatically reconnect after a transient disconnection and remain stable.

Step 3: Check for other issues

Check whether the instance performance meets your business requirements.

Check third-party tool settings.

If a third-party tool, such as Navicat or Compass, cannot connect to an ApsaraDB for MongoDB instance, the connection may fail due to incorrect instance or tool settings. Troubleshoot the issue as follows:

  1. Use Mongo Shell to test the connection.

    We recommend that you use the Mongo Shell tool to connect to the instance using the high-availability ConnectionStringURI endpoint for testing.

  2. Troubleshoot the issue based on the test result.

    • Connection successful: The instance is accessible. The issue is likely caused by incorrect settings in the third-party tool. Check the third-party tool settings.

    • Connection failed: The instance settings may be incorrect. Refer to this topic for troubleshooting (network, authorization, identity verification).

Common errors

Error message

Cause and solution

network error while attempting to run command 'isMaster' on host 'dds-xxxx.mongodb.rds.aliyuncs.com:3717' :exception: connect failed

  • Timed out after 3000ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. exception=(com.mongodb.MongoSocketReadException: Prematurely reached end of stream)

  • Socket recv() errno:54 Connection reset by peer x.x.x.x:27017

The instance may have reached its maximum connection limit and cannot establish new connections.

Solution:

  1. Check if the instance connection limit has been reached. For more information, see How do I query the number of connections?.

  2. Optimize connection usage. For more information, see What do I do if the number of connections to my instance reaches the upper limit?.

MongoDB.Driver.MongoWaitQueueFullException: The wait queue for acquiring a connection to server xxx is full.

The wait queue of the MongoDB driver is full. This can happen if the connection pool size is too small or if there are high-concurrency requests, resulting in no available connections.

Solution:

  1. First, check the connection pool configuration in your application, such as setting an appropriate pool size. For more information, see How do I limit the number of client connections?.

  2. If the issue persists after you adjust the program's configuration, check whether the MongoDB instance has exhausted its connection limit. For more information, see:

    1. How do I query the number of connections?

    2. What do I do if the number of connections to my instance reaches the upper limit?

(TooManyLogicalSessions) Unable to add session into the cache because the number of active sessions is too high.

Excessive concurrent connections may exhaust available sessions.

Solution:

  1. Troubleshoot connection failures caused by exhausted connections.

    1. How do I query the number of connections?

    2. What do I do if the number of connections to my instance reaches the upper limit?

  2. If the number of connections is normal, check if other performance metrics of the instance are sufficient for your business requirements.

    1. Use the node monitoring feature to check the usage of common resources, such as CPU and memory usage. This helps you determine whether the instance type meets your business requirements.

    2. If the instance type is too small for the high workload, change the instance configuration during off-peak hours.

  • getaddrinfo failed.

  • No suitable servers found (`serverSelectionTryOnce` set).

Check if the instance endpoint is correct. For more information about endpoints, see:

  • Failed to connect to 10.*.*.8:3717 after 5000 milliseconds, giving up.Error: couldn't connect to server 10.*.*.8:3717 (10.*.*.8), connection attempt failed

  • pymongo.errors.ServerSelectionTimeoutError: dds-xxxx.mongodb.rds.aliyuncs.com:3717: [Errno 113] No route to host,dds-xxxx.mongodb.rds.aliyuncs.com:3717

  • InvalidInstanceId.NotFound: The instance not in current vpc.

This error occurs when an ECS instance fails to connect to an ApsaraDB for MongoDB instance over a private network.

Solution:

  1. Check the whitelist settings. Ensure that the private IP address of the ECS instance is added to a whitelist of the ApsaraDB for MongoDB instance.

  2. Ensure that the ECS instance and the MongoDB instance can communicate with each other.

    If the ECS instance and the MongoDB instance are in the same VPC, they can connect directly over the private network. To connect instances across different VPCs, perform one of the following actions.

org.springframework.data.mongodb.UncategorizedMongoDbException: Timeout while receiving message; nested exception is com.mongodb.MongoSocketReadTimeoutException: Timeout while receiving message

  • "errmsg": "not master", "code": 10107, "codeName": "NotMaster"

  • "errmsg": "not master", "code": 10107, "codeName": "NotWritablePrimary"

  • Time out after 30000ms while waiting for a server that matches writableServerSelector.

  • Command failed with error 10107 (NotWritablePrimary): 'not primary' on server xxx.

  • Explain's child command cannot run on this node. Are you explaining a write command on a secondary?

  • not master and slaveOk=false.

  • MongoNotPrimaryException: Command failed with error 10107 (NotMaster): 'not master' on server xxx.

  • reason: TopologyDescription { type: 'ReplicaSetNoPrimary',...}

This error occurs when a write operation is attempted on a node that is not the primary node.

Cause: Write operations can be performed only on the primary node. If your service previously connected using the endpoint of the primary node, the connected node becomes a secondary node after a primary-secondary switchover. As a result, write operations fail.

Solution:

  • In a production environment, connect your application to the database using a ConnectionStringURI endpoint. If a node fails, a primary-secondary switchover will not affect the read and write operations of your application. For more information about endpoints, see:

  • Manually switch node roles. Switch the node that corresponds to the single-node endpoint used by your service to the primary node.

Design a reconnection mechanism and exception handling for your application. This ensures that your application can automatically reconnect after a transient disconnection and remain stable.

[Unauthorized] cloud instance error, disk locked, plz check and upgrade your disk quota,

The instance is locked because the disk space is exhausted.

Solution: Resolve instance locking or write failures caused by exhausted disk space.

(AuthenticationFailed) Authentication failed.

  • !xxx@dds-xxx.mongodb.rds.aliyuncs.com: event not found

The password of the database account contains special characters such as !@#$%^&*()_+=.

Solution: How do I resolve connection failures caused by special characters in the account or password of a connection string?.

error getting cluster ID: (CommandNotFound) replSetGetConfig is forbidden by cloud provider for security reason

ApsaraDB for MongoDB does not support the replSetGetConfig command. For more information, see Supported and unsupported commands in ApsaraDB for MongoDB

FAQ

How do I query the number of connections?

The maximum number of connections varies based on the Instance types of your ApsaraDB for MongoDB instance.

Note

The maximum number of connections applies to each node in an instance. For example, if you purchase a three-node replica set instance with 1 core and 2 GB of memory, the maximum number of connections for the primary and secondary nodes is 500 each. The hidden node does not provide services.

Console

  1. Go to the MongoDB Replica Set Instances page or the MongoDB Sharded Cluster Instances page. In the top navigation bar, select a region. Then, click the ID of the target instance.

  2. In the navigation pane on the left, click Monitoring Data.

  3. On the Monitoring Data page, view the Connections information for the instance.

    If the instance is a sharded cluster instance, you must select the Mongos node that your service currently uses in the upper-left corner of the page.

Command

  1. Connect to an instance using Mongo Shell.

  2. View the number of connections.

    Run the db.serverStatus().connections command.

    mgset-123456:PRIMARY> db.serverStatus().connections
    {
            "current" : 1,
            "available" : 999,
            "internal_current" : 10,
            "internal_available" : 990,
            "totalCreated" : 632
    }             

    Parameter description:

    • current: The number of established connections.

    • available: The number of available connections.

  3. Query the current connection sources.

    1. Switch to the admin database.

      use admin
    2. Run the db.runCommand({currentOp: 1, $all: true}) command.

      mgset-123456:PRIMARY> db.runCommand({currentOp: 1, $all:[{"active" : true}]})                    

    By analyzing the command output, you can query the source IP address of each connection to determine the number of connections from each client. For more information, see the official documentation.

How do I limit the number of client connections?

When you connect to a database using a Connection String URI, you can set the number of connections in a connection pool by adding &maxPoolSize=<integer> to the end of the URI. The following example shows how to use Mongo Shell to connect to a database. In this example, the number of connections is set to 10, the database account is test, and the authentication database is admin:

mongo "mongodb://test:****@dds-bp19f409d7512****-pub.mongodb.rds.aliyuncs.com:3717,dds-bp19f409d7512****-pub.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-6108****&maxPoolSize=10"
Note

For information about how to limit the number of connections in a connection pool for clients in different languages, see the MongoDB API documentation.

What do I do if the number of connections to my instance reaches the upper limit?

You can restart the instance, components, or nodes to temporarily release all connections.

Important

When you restart an instance, its nodes are restarted in sequence. Each node experiences a transient disconnection of about 30 seconds. If the instance contains many collections (more than 10,000), the disconnection may last longer. Before you restart the instance, make the proper business arrangements and ensure that your application has a reconnection mechanism.

To prevent this issue from recurring, we recommend that you make the following adjustments after you restart the instance:

How do I resolve connection failures caused by special characters in the account or password of a connection string?

When you connect to an ApsaraDB for MongoDB instance using Mongo Shell or program code, the connection fails if the password in the connection string contains special characters that cannot be recognized. These special characters include !@#$%^&*()_+=.

Solution: You must escape the special characters in the connection string based on the following rules:

! : %21
@ : %40
# : %23
$ : %24
% : %25
^ : %5e
& : %26
* : %2a
( : %28
) : %29
_ : %5f
+ : %2b
= : %3d

Example: If the password is ab@#c, escape the special characters in the connection string. The password becomes ab%40%23c.

How do I specify an authentication database in a connection?

The authentication database stores database accounts and passwords. A database account must be authenticated against the database to which it belongs.

Assume that the account and password are both test, and the test account belongs to the testdb database.

High-availability endpoint

When you use a ConnectionStringURI or ReadOnly ConnectionStringURI endpoint to connect to a database, you must set the authSource parameter to specify the database to which the database account belongs. If you do not configure this parameter, the database specified by <database> is used as the authentication database.

Examples:

  • After the test account is authenticated against the testdb database, the instance switches to the <database> database.

mongo "mongodb://test:test@<host1>:<port1>,<host2>:<port2>,...,<hostN>:<portN>/<database>?replicaSet=<replicaSet_value>&authSource=testdb"
  • After the test account is authenticated against the testdb database, the instance switches to the testdb database.

mongo "mongodb://test:test@<host1>:<port1>,<host2>:<port2>,...,<hostN>:<portN>/testdb?replicaSet=<replicaSet_value>"

Single-node endpoint

You can run one of the following commands to log on:

mongo --host $myhost --port $myport -u test -p test --authenticationDatabase testdb

Or

    mongo --host $myhost --port $myport
    mongo> use testdb
    mongo> db.auth("test", "test")

For more information about the parameters in an endpoint, see Connect to a replica set instance and Connect to a sharded cluster instance.

How do I use DMS to log on to a MongoDB database?

What client languages does ApsaraDB for MongoDB support?

ApsaraDB for MongoDB is fully compatible with MongoDB. This means that all clients supported by MongoDB are also supported by ApsaraDB for MongoDB.

Supported languages include C, C++, C#, Java, Node.js, Python, PHP, and Perl. For more information, see the official documentation.

For sample code, see:

Note

To ensure proper authentication when you connect to an ApsaraDB for MongoDB instance, use a MongoDB driver of version 3.0 or later.

Does ApsaraDB for MongoDB support public network access?

Does ApsaraDB for MongoDB support password-free access?

ApsaraDB for MongoDB no longer supports password-free access over a VPC.

If you have enabled password-free access for an instance, you can disable this feature. After you disable the feature, you cannot re-enable it. For information about how to disable password-free access, see Disable password-free access over a private network.

Install and use Mongo Shell on Windows

  • Install Mongo Shell. Go to the MongoDB Shell Download page, and follow the on-screen instructions to download and install it.

  • Use Mongo Shell.

    • Open Command Prompt.

    • Connect to the MongoDB instance.

      Example:

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

      For more information about the connection string parameters, see Connect to a replica set instance and Connect to a sharded cluster instance.

Common connection scenarios