pip install pymongo[srv].pip install pymongo
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
MongoClient has a built-in connection pool. Reuse the same instance throughout your application to avoid creating multiple instances.@, :, or /, use urllib.parse.quote_plus() to URL-encode it.connectTimeoutMS and socketTimeoutMS to prevent threads from being blocked for extended periods due to network issues.from pymongo import MongoClientfrom 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 poolminPoolSize=5, # Minimum size of the connection poolconnectTimeoutMS=10000, # Connection timeout of 10 secondssocketTimeoutMS=30000, # Socket timeout of 30 secondsretryWrites=True, # Enable retryable writesretryReads=True, # Enable retryable readsw="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
from pymongo import MongoClientfrom pymongo.errors import ConnectionFailure, OperationFailurefrom bson.objectid import ObjectIdfrom datetime import datetimedef 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 collectiondb = client["mydb"]collection = db["users"]# ========== Insert a Document ==========# Insert a single documentdoc = {"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 Documentsdocs = [{"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 Documentuser = 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()
Connection successfulInserted document ID: 6789abcdef1234567890abcdBatch Insert 2 DocumentsQuery 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: 35Update 1 DocumentDelete 3 DocumentsThe connection has been closed.
read_preference parameter:from pymongo import MongoClient, ReadPreferenceclient = 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)
pymongo.errors.OperationFailure: Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}
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"
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: Python 3.11.1
urllib.parse.quote_plus() to encode the password:from urllib.parse import quote_pluspassword = quote_plus("pass@123") # Output: pass%40123uri = f"mongodb://mongouser:{password}@10.66.187.127:27017/admin"
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: Python 3.11.1
pymongo.errors.ServerSelectionTimeoutError: 10.66.187.127:27017: [Errno 110] Connection timed out, Timeout: 30s
telnet <MongoDB-instance-IP> 27017
Connected indicates that the network is reachable.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.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
replicaSet parameter value matches the value displayed in the console:uri = "mongodb://mongouser:thepasswordA1@IP1:27017,IP2:27017/admin?replicaSet=cmgo-xxxxxxxx_0"
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: Python 3.11.1
pymongo.errors.AutoReconnect: connection was closed
retryWrites=True when creating the client. The driver automatically retries once:client = MongoClient(uri, retryWrites=True)
import timefrom pymongo.errors import AutoReconnectdef 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, 4sprint(f"Connection interrupted. Retrying in {wait_time} seconds (attempt {attempt + 1}): {e}")time.sleep(wait_time)else:raise
피드백