You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地连接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 named 104.211.182.12—that's not how this function works. You need to store your full Azure MongoDB connection string in an environment variable (like AZURE_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 initialize MongoClient—you don't need to call this method separately.

How to Get Your Azure Connection String

  1. Log into the Azure Portal and open your Cosmos DB account.
  2. Head to Settings > Connection Strings.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:51:06