本地连接Azure MongoDB失败,现有pymongo代码调试求助
How to Connect to Azure MongoDB Locally?
Let's walk through fixing your code to get a successful local connection to Azure Cosmos DB for MongoDB:
Corrected Working Code
from pymongo import MongoClient import os # Best practice: Store your connection string in an environment variable for security # Replace "AZURE_MONGODB_CONN_STR" with the name of your environment variable connection_string = os.getenv("AZURE_MONGODB_CONN_STR") client = MongoClient(connection_string) # Access your target database db = client.test_database # Quick check to confirm the connection works try: print("Connected successfully! Collections in database:", db.list_collection_names()) except Exception as e: print(f"Connection failed: {e}")
What Was Wrong With Your Original Code?
- Misused
os.getenv:os.getenv("104.211.182.12")is trying to pull an environment variable named104.211.182.12—that's not how this function works. You need to store your full Azure MongoDB connection string in an environment variable (likeAZURE_MONGODB_CONN_STR) and fetch that instead of the raw IP. - Missing required connection parameters: Azure Cosmos DB for MongoDB needs a specific connection format that includes your account name, password, host, port, and SSL settings. The valid connection string from Azure Portal looks like this:
mongodb://<your-account-name>:<your-password>@<your-account-name>.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@<your-account-name>@ - Redundant
db.authenticate: When you use the full connection string, authentication is handled automatically when you initializeMongoClient—you don't need to call this method separately.
How to Get Your Azure Connection String
- Log into the Azure Portal and open your Cosmos DB account.
- Head to Settings > Connection Strings.
- Copy the Primary Connection String (or Secondary) and use that in your code (either directly, or better, save it to an environment variable to keep credentials secure).
内容的提问来源于stack exchange,提问作者Adarsh R
相关产品推荐
相关产品推荐

