Scenarios
When integrating TencentDB for MongoDB into your application, you need to connect to the database instance using a driver for your programming language to read and write data. TencentDB for MongoDB is 100% compatible with the MongoDB protocol, so you can directly use the official MongoDB driver or popular community drivers to connect without any additional adaptation.
This document provides connection examples and usage guides for drivers in various programming languages to help you:
Quick Access: Get pre-validated connection code templates that include authentication configuration, connection pool setup, and error handling — ready to use out of the box.
Avoiding Common Issues: The examples clearly explain key points such as the authentication mechanism for TencentDB for MongoDB (authSource=admin), the network environment (VPC private network access), and escaping special characters in passwords.
Production-Ready Practices: Beyond basic connection setup, each language example includes key practices for production environments, such as connection pool configuration recommendations, exception handling, and resource release.
Preparing for Connection
Before using any language driver to connect to TencentDB for MongoDB, ensure that the following prerequisites are met:
A TencentDB for MongoDB instance has been created, and its status is Running. For specific operations, see Create MongoDB Instance. Prepare a CVM that resides in the same VPC as the TencentDB for MongoDB instance to serve as the connection client. TencentDB for MongoDB currently supports private network access by default, and public network access can be enabled.
You have obtained the database connection information. On the instance details page in the MongoDB console, obtain the following information: |
Private network address and port | Instance details > Network configuration | The format is IP address:27017, and the replica set instance provides multiple IP addresses. |
Username. | Default user mongouser, or created on the DMC page. | Users created on the console uniformly use admin as the authentication database. |
Password | Set during instance creation | If it contains special characters such as @, :, or /, URL encoding must be applied. |
Authentication database | Fixed to admin | Specify authSource=admin in the URI. |
Connection URI Format
TencentDB for MongoDB supports the standard MongoDB URI connection string format:
// Replica set instance
mongodb://mongouser:<password>@<IP1>:27017,<IP2>:27017,<IP3>:27017/<database>?authSource=admin&replicaSet=<replicaSetName>
// Sharded cluster instance (connect to the mongos node):
mongodb://mongouser:<password>@<mongosIP1>:27017,<mongosIP2>:27017/<database>?authSource=admin
Note:
Use the replica set connection string (which contains multiple IPs). The driver can automatically perform failover to enhance availability. For more information, see Connection and Security Specifications. To enable read/write splitting, add the readPreference=secondaryPreferred parameter to the URI to prioritize reading data from secondary nodes.
Special characters in the password (such as @, :, /, %) must be URL-encoded. For example, @ is encoded as %40.
Supported Language Drivers
TencentDB for MongoDB supports all official and community drivers that are compatible with the MongoDB protocol. The following are connection examples and recommended driver versions for each language:
|
Java | MongoDB Java Driver | 4.9 or above | | Enterprise backend applications, Spring ecosystem integration |
Python | PyMongo | 4.6 or above | | Data analysis, Web backend, script automation |
Go | MongoDB Go Driver | 1.13 or above | | High-concurrency backend services, microservices architecture |
Node.js | MongoDB Node.js Driver | 6.0 or above | | Web backend services, Serverless applications |
PHP | MongoDB PHP Library | 1.17 or above | | Web application development |
Note:
The versions listed above reflect the latest recommendations as of this document's last update. Make sure the driver version is compatible with your MongoDB instance version. For details on the compatibility of each driver version, see MongoDB Official Driver Compatibility Matrix. If you use other languages (such as C#, Ruby, Rust, and so on), see the MongoDB Official Driver List. The connection method is similar to the examples above, and the key point is to specify the authSource=admin authentication database. Authentication Method
TencentDB for MongoDB supports the following authentication methods:
Note:
Earlier instances may have the default user rwuser, which uses the MONGODB-CR authentication method. This authentication method is no longer recommended. If your instance has the rwuser user, migrate it to mongouser or create a new user.
|
SCRAM-SHA-1 | mongouser and all users created on the console
| As the default authentication method, it is compatible with all MongoDB versions, and clients do not need to explicitly specify the authMechanism parameter. |
SCRAM-SHA-256 | Users created on the console (MongoDB 4.0 and later versions) | A more secure authentication method. Client drivers 4.0 and later automatically negotiate and use it by default. To enforce its use, explicitly set authMechanism=SCRAM-SHA-256 in the connection string. |
Connection Pool Configuration Recommendations
In production environments, configure a connection pool to reuse database connections and avoid the performance overhead caused by frequently creating and destroying connections. The following are general configuration recommendations:
|
maxPoolSize
| 50 - 200 | The maximum size of the connection pool. Adjust this value based on your application's concurrency level and instance specifications. We recommend not exceeding 80% of the instance's maximum connections. |
minPoolSize
| 5 - 20 | 5 – 20The minimum size of the connection pool. Maintains a number of idle connections to reduce cold start latency. |
connectTimeoutMS
| 10000 | The connection timeout, in milliseconds. 10 seconds is sufficient for VPC environments. |
socketTimeoutMS
| 30000 | The socket timeout, in milliseconds. Adjust this value based on the complexity of your business queries. |
maxIdleTimeMS
| 60000 | The maximum lifetime of idle connections, in milliseconds. Prevents connections from being terminated by the server due to prolonged inactivity. |
retryWrites
| true | Enables retryable writes to improve write reliability in scenarios with network jitter. |
retryReads
| true | Enables retryable reads to improve read reliability. |
w
| majority | The write concern level. Ensures that acknowledgment is returned only after data is written to a majority of nodes. |
FAQs
How to Select a Driver Version?
The driver version must be compatible with the MongoDB instance version. An improper selection may cause connection failures or feature exceptions. See the following principles:
1. Use the recommended versions first: the recommended driver versions for each language are listed in the Supported Language Drivers table above. These versions have been verified to connect normally to TencentDB for MongoDB.
3. Avoid using deprecated drivers: The following drivers are no longer maintained. Migrate to their corresponding replacement drivers:
|
mongo-java-driver(Java 3.x) | mongodb-driver-sync (4.x and later) |
mgo (Go community driver) | go.mongodb.org/mongo-driver (official driver) |
PyMongo 3.x | PyMongo 4.x |
How to Handle Connection Timeouts or Slow Responses?
Connection timeouts or slow responses are usually caused by network latency, improper connection pool configuration, or query performance issues. Troubleshoot by following these steps:
1. Check network latency: Run the following command on the CVM to confirm the network latency to the MongoDB instance. The normal private network latency should be within 1 ms. If the latency is too high, check whether the CVM and the MongoDB instance are in the same AZ.
telnet <instance-access-IP-address> <port>
2. Check connection pool configuration: Improper connection pool configuration may cause connection wait timeouts. See Connection Pool Configuration Recommendations to adjust parameters and ensure that maxPoolSize matches the business concurrency. 3. Check slow queries: Log in to the MongoDB console, choose DMC > Slow Log Query on the instance management page, and check whether there are queries with excessively long execution times. If slow queries exist, optimize the query conditions or add indexes.