tencent cloud

TencentDB for MongoDB

Python SDK

다운로드
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-06-11 11:36:10

Scenarios

Python is widely used in scenarios such as web backend development, data analysis, and automation scripting, thanks to its concise syntax and rich ecosystem. PyMongo is the official Python driver maintained by MongoDB, providing synchronous APIs for database operations. This document walks you through a complete example of using PyMongo to connect to TencentDB for MongoDB, covering connection configuration and CRUD operations.

Prerequisites

You have created a TencentDB for MongoDB instance, and the instance status is Running.
You have prepared a CVM instance that resides in the same VPC as the MongoDB instance, and Python 3.8 or a later version is installed on it.

Installing a Driver

Install PyMongo 4.6 or a later version. If you need DNS SRV connection support, additionally install pip install pymongo[srv].
pip install pymongo

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)

Must-Knows

Python Version: The examples in this document are based on Python 3.8 or later. If you are still using Python 2.x, upgrade promptly, as PyMongo 4.x no longer supports Python 2.
Connection Reuse: MongoClient has a built-in connection pool. Reuse the same instance throughout your application to avoid creating multiple instances.
Password Escaping: If your password contains special characters such as @, :, or /, use urllib.parse.quote_plus() to URL-encode it.
Timeout Configuration: In production environments, configure connectTimeoutMS and socketTimeoutMS to prevent threads from being blocked for extended periods due to network issues.

Connection Example

Basic Connections

from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, OperationFailure

# Connection URI (Replace with your actual connection information)
uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin"

# Replica set connection string (Recommended, supports automatic failover):
# uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017,10.66.187.128:27017,10.66.187.129:27017/admin?replicaSet=cmgo-xxxxxxxx_0"

try:
# Create a client connection (Includes connection pool configuration)
client = MongoClient(
uri,
maxPoolSize=50, # Maximum size of the connection pool
minPoolSize=5, # Minimum size of the connection pool
connectTimeoutMS=10000, # Connection timeout of 10 seconds
socketTimeoutMS=30000, # Socket timeout of 30 seconds
retryWrites=True, # Enable retryable writes
retryReads=True, # Enable retryable reads
w="majority" # Write concern level
)

# Verify whether the connection is successful.
client.admin.command("ping")
print("Connection successful")

except ConnectionFailure as e:
print(f"Connection failure: {e}")
raise

CRUD Operation Examples

from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, OperationFailure
from bson.objectid import ObjectId
from datetime import datetime

def main():
uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin"

try:
client = MongoClient(uri, retryWrites=True, w="majority")
client.admin.command("ping")
print("Connection successful")

# Select a database and a collection
db = client["mydb"]
collection = db["users"]

# ========== Insert a Document ==========
# Insert a single document
doc = {
"username": "jack",
"age": 31,
"email": "jack@example.com",
"created_at": datetime.now()
}
result = collection.insert_one(doc)
print(f"Inserted document ID: {result.inserted_id}")

# Batch Insert Documents
docs = [
{"username": "alice", "age": 28, "email": "alice@example.com"},
{"username": "bob", "age": 35, "email": "bob@example.com"},
]
result = collection.insert_many(docs)
print(f"Batch inserted {len(result.inserted_ids)} documents")

# ========== Query Documents ==========
# Query a Single Document
user = collection.find_one({"username": "jack"})
print(f"Query a single document: {user}")

# Conditional Query (Age greater than 30)
cursor = collection.find({"age": {"$gt": 30}})
print("Users with age greater than 30:")
for doc in cursor:
print(f" - {doc['username']}, Age: {doc['age']}")

# ========== Update Documents ==========
result = collection.update_one(
{"username": "jack"},
{"$set": {"age": 32, "updated_at": datetime.now()}}
)
print(f"Updated {result.modified_count} documents")

# ========== Delete Documents ==========
result = collection.delete_many({"username": {"$in": ["jack", "alice", "bob"]}})
print(f"Deleted {result.deleted_count} documents")

except ConnectionFailure as e:
print(f"Connection failure: {e}")
except OperationFailure as e:
print(f"Operation failed: {e}")
finally:
client.close()
print("Connection closed")

if __name__ == "__main__":
main()
Sample Output:
Connection successful
Inserted document ID: 6789abcdef1234567890abcd
Batch Insert 2 Documents
Query a single document: {'_id': ObjectId('6789abcdef1234567890abcd'), 'username': 'jack', 'age': 31, 'email': 'jack@example.com', 'created_at': datetime.datetime(2026, 4, 17, -1, 0, 0)}
Users with age greater than 30:
- jack, age: 31
- bob, age: 35
Update 1 Document
Delete 3 Documents
The connection has been closed.

Read/Write Splitting Configuration

To read data from secondary nodes and reduce the load on the primary node, configure read/write splitting via the read_preference parameter:
from pymongo import MongoClient, ReadPreference

client = MongoClient(
"mongodb://mongouser:thepasswordA1@IP1:27017,IP2:27017,IP3:27017/admin?replicaSet=cmgo-xxxxxxxx_0",
readPreference="secondaryPreferred"
)

# Or specify at the collection level.
db = client["mydb"]
collection = db.get_collection("users", read_preference=ReadPreference.SECONDARY_PREFERRED)

FAQs

pymongo.errors.OperationFailure: Authentication failed

Error Message Example:
pymongo.errors.OperationFailure: Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}
Troubleshoot by following these steps:
1. Confirm that the authentication database is specified as admin in the URI.
# Correct: The URI path is /admin.
uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin"
# Correct: Specify the authentication database via the authSource parameter when connecting to the business database.
uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb?authSource=admin"

# Error: Authentication fails because the driver defaults to using the mydb database for authentication when connecting to the business database without specifying authSource.
uri = "mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb"

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: Python 3.11.1

2. Confirm that special characters in the password are URL-encoded: Use urllib.parse.quote_plus() to encode the password:
from urllib.parse import quote_plus

password = quote_plus("pass@123") # Output: pass%40123
uri = f"mongodb://mongouser:{password}@10.66.187.127:27017/admin"

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: Python 3.11.1

3. Confirm that the username and password are correct: Log in to the MongoDB console and verify the user information on the instance management page. If you forget the password, you can reset it in the console.

pymongo.errors.ServerSelectionTimeoutError

Error Message Example:
pymongo.errors.ServerSelectionTimeoutError: 10.66.187.127:27017: [Errno 110] Connection timed out, Timeout: 30s
Troubleshoot by following these steps:
1. Confirm network connectivity: Run the following command on the CVM to verify whether the network is reachable:
telnet <MongoDB-instance-IP> 27017
An output of Connected indicates that the network is reachable.
An output of Connection timed out indicates that the network is unreachable. Confirm that the CVM and the MongoDB instance are in the same VPC and check the security group rules.
2. Check the serverSelectionTimeoutMS configuration: The default Server Selection timeout for PyMongo is 30 seconds. To adjust it, you can set it via parameters:
client = MongoClient(uri, serverSelectionTimeoutMS=10000) # 10 seconds
3. Confirm that the replica set name is correct: If you are using a replica set connection string, confirm that the replicaSet parameter value matches the value displayed in the console:
uri = "mongodb://mongouser:thepasswordA1@IP1:27017,IP2:27017/admin?replicaSet=cmgo-xxxxxxxx_0"

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: Python 3.11.1

pymongo.errors.AutoReconnect

Error Message Example:
pymongo.errors.AutoReconnect: connection was closed
This error is usually caused by network jitter or a primary/secondary switchover. The troubleshooting steps are as follows:
1. Enable retryable writes: Set retryWrites=True when creating the client. The driver automatically retries once:
client = MongoClient(uri, retryWrites=True)
2. Add retry logic to your business code: For critical write operations, it is recommended to add a retry mechanism at the application layer:
import time
from pymongo.errors import AutoReconnect

def insert_with_retry(collection, document, max_retries=3):
for attempt in range(max_retries):
try:
return collection.insert_one(document)
except AutoReconnect as e:
if attempt < max_retries - 1:
wait_time = 2 ** attempt # Exponential backoff: 1s, 2s, 4s
print(f"Connection interrupted. Retrying in {wait_time} seconds (attempt {attempt + 1}): {e}")
time.sleep(wait_time)
else:
raise

도움말 및 지원

문제 해결에 도움이 되었나요?

피드백